-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuilding.cpp
More file actions
82 lines (67 loc) · 1.57 KB
/
Copy pathBuilding.cpp
File metadata and controls
82 lines (67 loc) · 1.57 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
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
const ll N = 1e5 + 5;
ll parent[N];
ll group_size[N];
void dsu_initialize(ll n)
{
for (ll i = 0; i < n; i++){
parent[i] = -1;
group_size[i] = 1;
}
}
ll dsu_find(ll node)
{
if (parent[node] == -1) return node;
ll leader = dsu_find(parent[node]);
parent[node] = leader;
return leader;
}
void dsu_union_by_size(ll node1, ll node2)
{
ll leaderA = dsu_find(node1);
ll leaderB = dsu_find(node2);
if (group_size[leaderA] > group_size[leaderB]) parent[leaderB] = leaderA,
group_size[leaderA] += group_size[leaderB];
else parent[leaderA] = leaderB, group_size[leaderB] += group_size[leaderA];
}
class Edge{
public:
ll u, v, w;
Edge(ll u, ll v, ll w){
this->u = u;
this->v = v;
this->w = w;
}
};
bool cmp(Edge a, Edge b){
return a.w < b.w;
}
int main(){
ll n, e;
cin >> n >> e;
dsu_initialize(n);
vector<Edge> edgeList;
while (e--){
ll u, v, w;
cin >> u >> v >> w;
edgeList.push_back(Edge(u, v, w));
}
sort(edgeList.begin(), edgeList.end(), cmp);
ll totalCost = 0;
ll connectedBuilding = n;
for (Edge ed : edgeList){
ll leaderU = dsu_find(ed.u);
ll leaderV = dsu_find(ed.v);
if (leaderU == leaderV) continue;
else{
dsu_union_by_size(ed.u, ed.v);
totalCost += ed.w;
connectedBuilding--;
}
}
if(connectedBuilding == 1) cout << totalCost;
else cout << -1;
return 0;
}