Sightseeing trip
Floyd最小环;
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> const int INF = 1e7+5; using namespace std; int n; int dis[105][105]; int d[105][105]; int path[105][105]; int ans[105]; void init(){ for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ d[i][j] = d[j][i] = dis[i][j] = dis[j][i] = INF; path[i][j] = i; } } } void floyd(){ int Min = INF; int cnt; for(int k = 1; k <= n; k++){ for(int i = 1; i < k; i++){ for(int j = i+1; j < k; j++){ if(dis[i][j] + d[i][k] + d[k][j] < Min){//若INF = 0x3f3f3f3f,三个数和会超出int范围; Min = dis[i][j] + d[i][k] + d[k][j]; cnt = 0; int p = j; while(p != i){ ans[cnt++] = p; p = path[i][p]; } ans[cnt++] = i; ans[cnt++] = k; } } } for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if(dis[i][j] > dis[i][k] + dis[k][j]){ dis[i][j] = dis[i][k] + dis[k][j]; path[i][j] = path[k][j]; } } } } if(Min == INF){ puts("No solution."); return; } for(int i = 0; i < cnt; i++){ if(i)printf(" "); printf("%d",ans[i]); } } int main(){ int m; scanf("%d%d", &n, &m); init(); for(int i = 0; i < m; i++){ int x, y, w; scanf("%d%d%d", &x, &y, &w); if(w < d[x][y]){ d[x][y] = d[y][x] = dis[x][y] = dis[y][x] = w; } } floyd(); return 0; }