POJ 1734
#include<iostream> #include<stdio.h> #define MAXN 105 #define inf 123456789 using namespace std; int _m[MAXN][MAXN]; int floy[MAXN][MAXN]; int pre[MAXN][MAXN]; int ans[MAXN]; int n; int num; void floyd(); int main() { //freopen("acm.acm","r",stdin); int m; int u; int v; int i; int j; int len; memset(_m,0,sizeof(_m)); memset(pre,-1,sizeof(pre)); cin>>n>>m; for(i = 0; i < n; ++ i) { for(j = 0; j <n; ++ j) { floy[i][j] = inf; floy[j][i] = inf; } floy[i][i] = 0; } for(i = 0; i < m; ++ i) { cin>>u>>v>>len; -- u; -- v; if(floy[u][v] > len) { _m[u][v] = _m[v][u] = len; floy[u][v] = floy[v][u] = len; pre[u][v] = v; pre[v][u] = u; } } floyd(); if(num == 0) { cout<<"No solution."<<endl; } else { for(i = 0; i < num; ++ i) { cout<<ans[i]+1<<" "; } cout<<endl; } } void floyd() { int k; int i; int j; int min = inf; int temp; num = 0; for(k = 0; k < n; ++ k) { for(i = 0; i < k; ++ i) { for(j = 0; j < k; ++ j) { if(_m[i][k] && _m[k][j] && i != j) { if(_m[i][k] + _m[k][j] + floy[i][j] < min) { min = _m[i][k] + _m[k][j] + floy[i][j]; ans[0] = k; num = 1; int p = i; while(p != -1) { ans[num ++] = p; p = pre[p][j]; // cout<<"00000000000"<<endl; // cout<<p<<endl; } // return ; } } } } for(i = 0; i < n; ++ i) { for(j = 0; j < n; ++ j) { if(floy[i][k] + floy[k][j] < floy[i][j]) { floy[i][j] = floy[i][k] + floy[k][j]; pre[i][j] = pre[i][k]; } } } } }
关注我的公众号,当然,如果你对Java, Scala, Python等技术经验,以及编程日记,感兴趣的话。
技术网站地址: vmfor.com