find the mincost route【无向图最小环】

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1599

Problem Description
杭州有N个景区,景区之间有一些双向的路来连接,现在8600想找一条旅游路线,这个路线从A点出发并且最后回到A点,假设经过的路线为V1,V2,....VK,V1,那么必须满足K>2,就是说至除了出发点以外至少要经过2个其他不同的景区,而且不能重复经过同一个景区。现在8600需要你帮他找一条这样的路线,并且花费越少越好。
Input
第一行是2个整数N和M(N <= 100, M <= 1000),代表景区的个数和道路的条数。
接下来的M行里,每行包括3个整数a,b,c.代表a和b之间有一条通路,并且需要花费c元(c <= 100)。
Output
对于每个测试实例,如果能找到这样一条路线的话,输出花费的最小值。如果找不到的话,输出"It's impossible.".
Sample Input
3 3
1 2 1
2 3 1
1 3 1
3 3
1 2 1
1 2 3
2 3 1
Sample Output
3
It's impossible.
题目大意:给一张n个点,m条无向边的图,求图中最小环长度。
解题思路:
1.floyd最小环模板
2.注意inf为0x3f3f3f3f时,三个inf相加会爆int ,所以数组我们开long long型
代码如下:
 1 #include<stdio.h>
 2 #include<algorithm>
 3 #define LL long long
 4 #define mem(a, b) memset(a, b, sizeof(a))
 5 using namespace std;
 6 const LL inf = 0x3f3f3f3f;
 7 const int MAXN = 110;
 8 
 9 int n, m;
10 LL dis[MAXN][MAXN], map[MAXN][MAXN];//最短路径 直接路径 
11 LL ans;
12 
13 void floyd()
14 {
15     ans = inf;
16     for(int k = 1; k <= n; k ++) //枚举中点 
17     {
18         for(int i = 1; i < k; i ++) //起点 
19             for(int j = i + 1; j < k; j ++)//终点 
20                 ans = min(ans, map[i][k] + map[k][j] + dis[i][j]); //在dis没更新倒k之前,是没有经过k点的。所以保证了至少3个不同的点 
21         for(int i = 1; i <= n; i ++)
22             for(int j = 1; j <= n; j ++)
23                 dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
24     }
25     if(ans != inf)
26         printf("%lld\n", ans);
27     else
28         printf("It's impossible.\n");
29 }
30 
31 int main()
32 {
33     while(scanf("%d%d", &n, &m) != EOF)
34     {
35         for(int i = 1; i <= n; i ++)
36             for(int j = 1; j <= n; j ++)
37             {
38                 if(i == j)
39                     dis[i][j] = map[i][j] = 0;
40                 else
41                     dis[i][j] = map[i][j] = inf;
42             }
43         for(int i = 1; i <= m; i ++)
44         {
45             int a, b;
46             LL c;
47             scanf("%d%d%lld", &a, &b, &c);
48             dis[a][b] = dis[b][a] = map[a][b] = map[b][a] = min(map[a][b], c);//双向边 
49         }
50         floyd();
51     }
52     return 0;
53 }
View Code

猜你喜欢

转载自www.cnblogs.com/yuanweidao/p/11517084.html
今日推荐