题目链接 : http://acm.hust.edu.cn/vjudge/contest/view.action?cid=121378#problem/D
题意 : 有n个农场,现给定一个指定农场,让各个农场的牛去参加party,然后各自返回各自的农场,问在这些牛之中,所用来回时间和最大的是多少?
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #define maxn 11000 #define oo 0x3f3f3f3f int maps[maxn][maxn],dist[maxn],v[maxn],backs[maxn]; int n,m,x; void Init() { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) { if(i==j) maps[i][j]=0; else maps[i][j]=maps[j][i]=oo; } } int Dij() { int i,j; memset(v,0,sizeof(v)); for(i=1; i<=n; i++) { dist[i]=maps[x][i]; backs[i]=maps[i][x]; } v[x]=1; for(i=1; i<=n; i++) { int mins=oo, Index; for(j=1; j<=n; j++) if(dist[j]<mins &&!v[j]) { mins=dist[j]; Index=j; } v[Index]=1; for(j=1; j<=n; j++) { if(dist[j]>mins+maps[Index][j] &&!v[j]) { dist[j]=mins+maps[Index][j]; } } } memset(v,0,sizeof(v)); v[x]=1; for(i=1; i<=n; i++) { int mins=oo, Index=0; for(j=1; j<=n; j++) if(backs[j]<mins &&! v[j]) { mins=backs[j]; Index=j; } v[Index]=1; for(j=1; j<=n; j++) { if(backs[j]>mins+maps[j][Index] && !v[j]) { backs[j]=mins+maps[j][Index]; } } } int ans=-1; for(i=1; i<=n; i++) { if(ans<dist[i]+backs[i]) ans=dist[i]+backs[i]; } return ans; } int main() { int a, b, c, i; while(scanf("%d%d%d",&n,&m,&x)!=EOF) { Init(); for(i=1; i<=m; i++) { scanf("%d%d%d",&a, &b, &c); maps[a][b]=min(maps[a][b], c); } int ans=Dij(); printf("%d\n",ans); } return 0; }