题目链接:http://poj.org/problem?id=1734
AC代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<vector> 5 using namespace std; 6 const int N=105; 7 int n,m; 8 int ans=0x3f3f3f; 9 int a[N][N],d[N][N],pos[N][N]; 10 vector<int> path; 11 void get_path(int x,int y){ 12 if(pos[x][y]==0) return; 13 get_path(x,pos[x][y]); 14 path.push_back(pos[x][y]); 15 get_path(pos[x][y],y); 16 } 17 int main(){ 18 scanf("%d%d",&n,&m); 19 memset(a,0x3f,sizeof(a)); 20 for(int i=1;i<=n;i++) a[i][i]=0; 21 for(int i=1;i<=m;i++){ 22 int u,v,w; 23 scanf("%d%d%d",&u,&v,&w); 24 a[u][v]=a[v][u]=min(a[u][v],w); 25 } 26 memcpy(d,a,sizeof(a)); 27 for(int k=1;k<=n;k++){ 28 for(int i=1;i<k;i++) 29 for(int j=i+1;j<k;j++) 30 if((long long)d[i][j]+a[j][k]+a[k][i]<ans){ 31 ans=d[i][j]+a[j][k]+a[k][i]; 32 path.clear(); 33 path.push_back(i); 34 get_path(i,j); 35 path.push_back(j); 36 path.push_back(k); 37 } 38 for(int i=1;i<=n;i++) 39 for(int j=1;j<=n;j++) 40 if(d[i][j]>d[i][k]+d[k][j]){ 41 d[i][j]=d[i][k]+d[k][j]; 42 pos[i][j]=k; 43 } 44 } 45 if(ans==0x3f3f3f){ 46 printf("No solution. "); 47 return 0; 48 } 49 for(int i=0;i<path.size();i++) printf("%d ",path[i]); 50 return 0; 51 }