PAT L3-005. 垃圾箱分布
最短路。
枚举垃圾箱放哪里,然后算最短路。
#include<map> #include<set> #include<ctime> #include<cmath> #include<queue> #include<string> #include<stack> #include<vector> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<functional> using namespace std; int n,m,k,ds; char u[10]; vector<int>g[2000]; int v[1100][1100]; int dis[1100], f[1100]; int fail=1; int ansLen=-1,avg=-1,id=-1; int get() { int sum=0; if(u[0]!='G') { for(int i=0;u[i];i++) sum=sum*10+u[i]-'0'; } else { for(int i=1;u[i];i++) sum=sum*10+u[i]-'0'; sum = sum + n; } return sum; } void spfa(int x) { for(int i=1;i<=n+m;i++) dis[i] = 0x7FFFFFFF; queue<int>Q; memset(f,0,sizeof f); dis[x]=0; f[x]=1; Q.push(x); while(!Q.empty()) { int h= Q.front(); Q.pop(); f[h]=0; for(int i=0;i<g[h].size();i++) { int to = g[h][i]; if(dis[h]+v[h][to]<dis[to]) { dis[to] = dis[h]+v[h][to]; if(f[to]==0) { f[to]=1; Q.push(to); } } } } for(int i=1;i<=n;i++) if(dis[i]>ds) return ; fail=0; int mi=0x7FFFFFFF,sum=0; for(int i=1;i<=n;i++) sum=sum+dis[i],mi = min(mi,dis[i]); if(id==-1) { id = x; ansLen = mi; avg = sum; } else { if(mi>ansLen) { id = x; ansLen = mi; avg = sum; } else if(mi==ansLen) { if(sum<avg) { id = x; ansLen = mi; avg = sum; } } } } int main() { scanf("%d%d%d%d",&n,&m,&k,&ds); for(int i=1;i<=k;i++) { int c; scanf("%s",u); int A = get(); scanf("%s",u); int B = get(); scanf("%d",&c); v[A][B]=v[B][A]=c; g[A].push_back(B); g[B].push_back(A); } for(int i=n+1;i<=n+m;i++) { spfa(i); } if(fail) printf("No Solution\n"); else { printf("G%d\n",id-n); printf("%.1f %.1f\n",1.0*ansLen,1.0*avg/n); } return 0; }