POJ 1734 Sightseeing trip(无向图最小环+输出路径)

题目链接

 1 #include 
 2 #include <string>
 3 #include 
 4 #include 
 5 #include 
 6 #include 
 7 using namespace std;
 8 #define LL __int64
 9 #define MOD 1000000007
10 #define INF 0xffffff
11 int dp[101][101],g[101][101],pre[101][101];
12 int ans[1001];
13 int main()
14 {
15     int n,m,minz,i,j,k,sv,ev,w,num,temp;
16     while(scanf("%d%d",&n,&m)!=EOF)
17     {
18         memset(pre,-1,sizeof(pre));
19         for(i = 1; i <= n; i ++)
20         {
21             for(j = 1; j <= n; j ++)
22                 dp[i][j] = g[i][j] = INF;
23             dp[i][i] = g[i][i] = 0;
24         }
25         for(i = 1; i <= m; i ++)
26         {
27             scanf("%d%d%d",&sv,&ev,&w);
28             g[sv][ev] = dp[sv][ev] = min(dp[sv][ev],w);
29             g[ev][sv] = dp[ev][sv] = min(dp[ev][sv],w);
30             pre[sv][ev] = ev;
31             pre[ev][sv] = sv;
32         }
33         minz = INF;
34         for(i = 1; i <= n; i ++)//求最小环
35         {
36             for(j = 1; j <= i-1; j ++)
37                 for(k = j+1; k <= i-1; k ++)
38                 {
39                     if(minz > dp[j][k] + g[j][i] + g[i][k])
40                     {
41                         minz = dp[j][k] + g[j][i] + g[i][k];
42                         num = 1;
43                         ans[0] = i;
44                         temp = j;
45                         while(temp != -1)
46                         {
47                             ans[num++] = temp;
48                             temp = pre[temp][k];
49                         }
50                     }
51                 }
52             for(j = 1; j <= n; j ++)
53                 for(k = 1; k <= n; k ++)
54                 {
55                     if(dp[j][k] > dp[j][i] + dp[i][k])
56                     {
57                         dp[j][k] = dp[j][i] + dp[i][k];
58                         pre[j][k] = pre[j][i];
59                     }
60                 }
61         }
62         if(minz == INF)
63         printf("No solution.\n");
64         else
65         {
66             for(i = 0;i < num;i ++)
67             {
68                 if(i == 0)
69                 printf("%d",ans[i]);
70                 else
71                 printf(" %d",ans[i]);
72             }
73         }
74         printf("\n");
75     }
76     return 0;
77 }

 

转载于:https://www.cnblogs.com/naix-x/p/3247486.html

你可能感兴趣的:(POJ 1734 Sightseeing trip(无向图最小环+输出路径))