0
点赞
收藏
分享

微信扫一扫

题236.pat甲级练习-1072 Gas Station (30 分)

343d85639154 2022-03-11 阅读 58

文章目录


题236.pat甲级练习-1072 Gas Station (30 分)


一、题目

在这里插入图片描述
在这里插入图片描述

二、题解

#include <bits/stdc++.h>

using namespace std;

typedef pair<int,int> pii;
const int add=1000;//因为房子从1编号到1000,所以1000之后没有被编号,那就用来给加油站编号
const int maxn=add+11;//加上加油站,编号共编到1010
const int Inf=0x3f3f3f3f;

struct Node
{
    int index;
    int dist;
    bool operator < (const Node &a) const
    {
        return dist>a.dist;
    }
};

int N,M,K,Ds;
priority_queue<Node> pq;
vector<pii> G[maxn];
int collected[maxn];
int dist[maxn];
int bestpos;
double maxminpath,minaverpath=Inf;
int flag;

void Dijkstra(int s)
{
    fill(dist,dist+maxn,Inf);
    fill(collected,collected+maxn,0);
    dist[s]=0;
    pq.push(Node{s,0});
    while(!pq.empty())
    {
        int minv=pq.top().index;
        pq.pop();
        if(collected[minv])
        {
            continue;
        }
        collected[minv]=1;
        for(int i=0;i<(int)G[minv].size();i++)
        {
            int v=G[minv][i].first;
            int w=G[minv][i].second;
            if(!collected[v]&&dist[v]>dist[minv]+w)//满足松弛条件,做松弛操作,并将新权放入pq
            {
                dist[v]=dist[minv]+w;
                pq.push(Node{v,dist[v]});
            }
        }
    }
}

int main()
{
    cin>>N>>M>>K>>Ds;
    for(int i=0;i<K;i++)
    {
        int u,v,w;
        string str_u,str_v;
        cin>>str_u>>str_v>>w;
        if(str_u[0]=='G')
        {
            u=stoi(str_u.substr(1,str_u.length()-1))+add;
        }
        else
        {
            u=stoi(str_u);
        }
        if(str_v[0]=='G')
        {
            v=stoi(str_v.substr(1,str_v.length()-1))+add;
        }
        else
        {
            v=stoi(str_v);
        }
        G[u].push_back({v,w});
        G[v].push_back({u,w});
    }
    for(int i=1;i<=M;i++)
    {
        Dijkstra(i+add);
        int j;
        double pathsum=0,averpath,nowminpath=Inf;
        for(j=1;j<=N;j++)
        {
            if(dist[j]>Ds)
            {
                break;
            }
            pathsum+=dist[j];
            nowminpath=min(nowminpath,(double)dist[j]);
        }
        if(j>N)
        {
            averpath=pathsum/N;
            flag=1;
        }
        else
        {
            continue;
        }
        if(nowminpath>maxminpath)//本题要的是加油站到house中的最大最小距离,即这个最小距离要在所有的最小距离中是最大的
        {
            minaverpath=averpath;
            maxminpath=nowminpath;
            bestpos=i;
        }
        else if(nowminpath==maxminpath)
        {
            if(averpath<minaverpath)//其次考虑加油站到houses的平均距离要最小
            {
                minaverpath=averpath;
                bestpos=i;
            }
        }
    }
    if(!flag)
    {
        printf("No Solution");
    }
    else
    {
        printf("G%d\n",bestpos);
        printf("%.1lf %.1lf",maxminpath,minaverpath);
    }
}


举报

相关推荐

0 条评论