【Kruskal】P3366 【模板】最小生成树

 1 #include 
 2 #include 
 3 using namespace std;
 4 
 5 struct Node
 6 {
 7     int u, v, w;
 8 }node[200005];
 9 
10 int s[5005];
11 int n, m;
12 int cnt;
13 int sum;
14 
15 bool cmp(Node a, Node b)
16 {
17     return a.w < b.w;
18 }
19 
20 int find(int a)
21 {
22     while (a != s[a])
23     {
24         s[a] = s[s[a]];
25         a = s[a];
26     }
27     return a;
28 }
29 
30 void kruskal()
31 {
32     sort(node, node + m, cmp);
33     for (int i = 0; i < m; i++)
34     {
35         int t1, t2;
36         t1 = find(node[i].u);
37         t2 = find(node[i].v);
38         if (t1 == t2)
39         {
40             continue;
41         }//通过并查集检测两节点是否连通
42         sum += node[i].w;
43         s[t2] = t1;
44         cnt++;
45         if (cnt == n - 1) break;
46     }
47 }
48 int main()
49 {
50     cin >> n >> m;
51     for (int i = 1; i <= n; i++)
52     {
53         s[i] = i;
54     }
55     for (int i = 0; i < m; i++)
56     {
57         cin >> node[i].u >> node[i].v >> node[i].w;
58     }
59     kruskal();
60     cout << sum;
61 }
View Code

 

你可能感兴趣的:(【Kruskal】P3366 【模板】最小生成树)