-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboj1647.cpp
More file actions
93 lines (74 loc) · 1.55 KB
/
boj1647.cpp
File metadata and controls
93 lines (74 loc) · 1.55 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
using p = pair<int, int>;
const int MAX = 1e6+3;
inline void Quick_IO() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
int parent[MAX];
int ranks[MAX];
int find(int a){
if(parent[a]==a) return a;
else{
return parent[a] = find(parent[a]);
}
}
void _union(int a, int b){
int x = find(a);
int y = find(b);
if(x==y) return;
if(ranks[x]>ranks[y]) {
swap(x, y);
}
parent[x] = y;
if(ranks[x]==ranks[y]) {
ranks[y]++;
}
}
struct edge {
p coord;
int distance;
edge(p a, int b) {
coord = a;
distance = b;
}
};
struct compare {
bool operator()(edge a, edge b) {
return a.distance > b.distance;
}
};
int N, M;
priority_queue<edge, vector<edge>, compare> pq;
int main() {
Quick_IO();
cin >> N>>M;
for (int i = 1; i <= N; ++i) parent[i] = i;
for (int i = 0, a, b, c; i < M; ++i) {
cin>>a>>b>>c;
pq.push(edge(p(a, b), c));
}
int counts = 0;
int answer = 0;
int div = 0;
while(!pq.empty()){
if(counts==N) break;
auto [currCoord, currDistance] = pq.top();
auto [currX, currY] = currCoord;
pq.pop();
if(find(currX)==find(currY)){
continue;
}else{
counts++;
_union(currX, currY);
answer += currDistance;
div = max(currDistance, div);
}
}
cout<<answer - div<<'\n';
return 0;
}