团体程序设计天梯赛-练习集-L3-005. 垃圾箱分布(最短路dijkstra)

记录一个菜逼的成长。。

题目链接

对每一个垃圾桶都用一遍dijkstra,然后把相应的数据存入结构体排下序,再输出就可以了
输出的时候注意下精度。
如果有一个居民点和垃圾桶间没有路径,这肯定是不行的。

#include 
#include 
#include 
#include 
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define ALL(v) (v).begin(),(v).end()
#define MIN(a,b) a < b ? a : b
#define MAX(a,b) a < b ? b : a
#define pb push_back
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 1000 + 50;
int dis[maxn][maxn],g[maxn][maxn],vis[maxn];
void init(int n)
{
    for( int i = 0; i < n + 20; i++ )
    for( int j = 0; j < n + 20; j++ )
        g[i][j] = INF;
}
int getnum(int st,char *a)
{
    int ret = 0;
    for( int i = st; a[i]; i++ )
        ret = ret * 10 + a[i] - '0';
    return ret;
}
void dijkstra(int s,int n,int m,int dis[])
{
    cl(vis,0);
    fill(dis,dis+n+m+1,INF);
    dis[s]=0;
    for(int i=1;iint mn=INF,x;
        for(int j=1;j<=n+m;j++){
            if(!vis[j]&&dis[j]1;
        for(int j=1;j<=n+m;j++){
            dis[j]=min(dis[j],dis[x]+g[x][j]);
        }
    }
}

struct Node{
    int d,id;
    double avg_dis;
    Node(){}
    Node(int a,double b,int c):d(a),avg_dis(b),id(c){}
};
vectorans;
bool cmp(Node a,Node b)
{
    if(a.d != b.d)return a.d > b.d;
    else if(a.avg_dis != b.avg_dis)return a.avg_dis < b.avg_dis;
    return a.id < b.id;
}
int main()
{
    int n,m,k,ds;
    while(~scanf("%d%d%d%d",&n,&m,&k,&ds)){
        char a[10],b[10];
        init(n);
        int u,v,w;
        for( int i = 0; i < k; i++ ){
            scanf("%s%s%d",a,b,&w);
            if(a[0] == 'G')u = getnum(1,a), u += n;
            else u = getnum(0,a);
            if(b[0] == 'G')v = getnum(1,b),v += n;
            else v = getnum(0,b);
            g[u][v] = MIN(w,g[u][v]);
            g[v][u] = g[u][v];
        }
        for( int i = n+1; i <= n + m; i++ )
            dijkstra(i,n,m,dis[i]);
        int flag = 1;
        for( int i = n + 1; i <= n+m; i++ ){
            int mn = INF,mx = 0;
            int sum = 0;
            for( int j = 1; j <= n; j++ ){
                mn = MIN(mn,dis[i][j]);
                mx = MAX(mx,dis[i][j]);
                if(dis[i][j] != INF)
                    sum += dis[i][j];
                else {flag = 0;break;}
            }
            if(!flag)break;
            if(mx <= ds){
                ans.pb(Node(mn,(double)sum / n,i-n));
            }
        }
        if(!flag){
            puts("No Solution");
        }
        else {
            if(!ans.size()){puts("No Solution");return 0;}
            sort(ALL(ans),cmp);
            printf("G%d\n%d.0 %.1f\n",ans[0].id,ans[0].d,ans[0].avg_dis+0.00001);
        }
    }
    return 0;
}

你可能感兴趣的:(图论,图论,最短路,PAT,cccc-gplt)