参考代码:https://blog.csdn.net/yo_bc/article/details/75042688
POJ-1734
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 const int MAX = 100+9; 5 const int _inf = 0x7fffffff; 6 const int INF = _inf/3;//可能会出现三个inf相加 7 8 int n,m; 9 int dis[MAX][MAX]; 10 int map[MAX][MAX]; 11 int pre[MAX][MAX],path[MAX];//用于打印路径 12 13 void init() { 14 for(int i = 1; i <= n; i++) { 15 for(int j = 1; j <= n; j++) { 16 pre[i][j] = i; 17 map[i][j] = dis[i][j] = INF; 18 } 19 map[i][i] = dis[i][i] = 0; 20 } 21 } 22 23 void folyd() { 24 int mins = INF; 25 int tmp; 26 int cnt ,sum; 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 tmp = dis[i][j] + map[i][k] + map[k][j]; 31 if(mins > tmp) { 32 mins = tmp; 33 cnt = 0, sum = 1; 34 //cnt 用于更新路径path: 因为最短环在改变,所以路径也会变 35 //sun 用于统计不同最小环的个数(i,j相同时可根据k区分,相同k可根据i,j区分,所以不会重???) 36 int t = i;//注:这里的环是 j--k--i....j 所以前一个是 i 37 while(t != j) {//递推找路径 38 path[cnt++] = t; 39 t = pre[j][t]; 40 } 41 path[cnt++] = j;//t==j 时退出后,前一个是j 42 path[cnt++] = k;//不是很懂这个耶......... 43 } 44 else if(mins == tmp) ++sum;//长度相同只是路径不同(虽然这题没用到) 45 } 46 } 47 48 for(int i = 1; i <= n; i++) { 49 for(int j = 1; j <= n; j++) { 50 if(dis[i][j] > dis[i][k] + dis[k][j]) { 51 dis[i][j] = dis[i][k] + dis[k][j]; 52 pre[i][j] = pre[k][j];//更新了最短路,pre自然要更新 53 } 54 55 } 56 } 57 } 58 59 if(mins == INF ) puts("No solution."); 60 else { 61 for(int i = cnt-1; i > 0; --i) printf("%d ",path[i]); 62 printf("%d",path[0]);//格式要对哟 63 } 64 } 65 66 int main() { 67 while(~scanf("%d %d",&n,&m)) { 68 init();//初始化 69 int a,b,c; 70 for(int i = 1; i <= m; i++) { 71 scanf("%d%d%d",&a,&b,&c); 72 map[b][a] = map[a][b] = dis[b][a] = dis[a][b] = min(dis[a][b],c); 73 } 74 folyd(); 75 } 76 return 0; 77 }
原文地址:https://www.cnblogs.com/virtualtan/p/10778118.html
时间: 2024-10-17 20:22:50