-
Notifications
You must be signed in to change notification settings - Fork 0
/
AcWing859.cpp
66 lines (66 loc) · 1.06 KB
/
AcWing859.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int M = 200100;
const int N = 100100;
int n, m, p[N];
struct Edge
{
int a;
int b;
int w;
bool operator<(const Edge& W) const
{
return w < W.w;
}
}edges[M];
int find(int x)
{
if(x != p[x]) p[x] = find(p[x]);
return p[x];
}
void Kruskal()
{
//初始化并查集
for(int i = 1; i <= n; i++)
{
p[i] = i;
}
sort(edges, edges + m);
int res = 0, cnt = 0;
for(int i = 0; i < m; i++)
{
int a = edges[i].a;
int b = edges[i].b;
int w = edges[i].w;
a = find(a);
b = find(b);
if(a != b)
{
//合并并查集
p[a] = b;
res += w;
cnt ++;
}
}
if (cnt < n - 1)
{
cout<<"impossible";
}
else
{
cout<<res;
}
}
int main()
{
cin >> n >> m;
int a, b, w;
for (int i = 0; i < m; i++)
{
cin >> a >> b >> w;
edges[i] = {a, b, w};
}
Kruskal();
}