POJ - 1797 Heavy Transportation

直接Kruskal

但是注意一点的是 从起点到终点 

只要起点和终点连通就可以停止添加路径了 因为再添加 就会减小weight最小的路

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string>
 4 #include <string.h>
 5 #include <map>
 6 #include <queue>
 7 #include <fstream>
 8 #include <algorithm>
 9 #include <string.h>
10 #define READ() freopen("in.txt", "r", stdin);
11 #define MAXV 1007
12 #define MAXE 1000007
13 
14 using namespace std;
15 
16 struct Edge
17 {
18     int from, to, cost;
19     Edge () {}
20     Edge (int from, int to, int cost) : from(from), to(to), cost(cost) {}
21 }edge[MAXE];
22 int num = 0;
23 void Add(int from, int to, int cost)
24 {
25     edge[num++] = Edge(from, to, cost);
26 }
27 int par[MAXV];
28 int find(int x)
29 {
30     if (x == par[x]) return x;
31     else return par[x] = find(par[x]);
32 }
33 void unite(int x, int y)
34 {
35     int px = find(x), py = find(y);
36     if (px == py) return ;
37     else par[py] = px;
38 }
39 bool same(int x, int y)
40 {
41     int px = find(x), py = find(y);
42     return px == py;
43 }
44 
45 bool cmp(Edge e1, Edge e2)
46 {
47     return e1.cost > e2.cost;
48 }
49 
50 int dist[MAXE];
51 int n, m;
52 int Kruskal()
53 {
54     int n1 = 0;
55     sort(edge, edge+num, cmp);
56     for (int i = 0; i < num; i++)
57     {
58         Edge e = edge[i];
59         if (!same(e.from, e.to))
60         {
61             unite(e.from, e.to);
62             dist[n1++] = e.cost;
63         }
64         if (same(1, n)) break;
65     }
66     sort(dist, dist+n1);
67     return dist[0];
68 }
69 int main()
70 {
71     READ()
72     int T,cnt = 1;
73     scanf("%d", &T);
74     while (T--)
75     {
76         scanf("%d%d", &n, &m);
77         for (int i = 1;i <= n; i++) par[i] = i;
78         memset(edge, 0, sizeof(edge));
79         for (int i = 0; i < m; i++)
80         {
81             int from, to, cost;
82             scanf("%d%d%d", &from, &to, &cost);
83             Add(from, to, cost);
84             Add(to, from, cost);
85         }
86         int ans = Kruskal();
87         printf("Scenario #%d:\n%d\n\n", cnt++, ans);
88     }
89 }

 

转载于:https://www.cnblogs.com/oscar-cnblogs/p/6435464.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值