-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1197.cpp
More file actions
61 lines (49 loc) · 967 Bytes
/
1197.cpp
File metadata and controls
61 lines (49 loc) · 967 Bytes
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
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define MAXN 10050
int parent[MAXN];
int V,E,ans=0;
bool valid;
struct edge{
int src,dst,val;
};
vector<edge> v;
bool cmp(edge a, edge b){
return a.val < b.val;
}
int find(int x){
if(parent[x] == x) return x;
return parent[x] = find(parent[x]);
}
void merge(int x, int y){
valid = false;
x = find(x);
y = find(y);
if(x == y){
return;
}
parent[x] = y;
valid = true;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> V >> E;
for(int i=0 ; i<=V ; i++) parent[i]=i;
for(int i=0 ; i<E ; i++){
edge e;
cin >> e.src >> e.dst >> e.val;
v.push_back(e);
}
sort(v.begin(), v.end(), cmp);
for(int i=0 ; i<E ; i++){
merge(v[i].src, v[i].dst);
if(valid){
ans += v[i].val;
}
}
cout << ans;
}