-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathRoad Reparation
More file actions
61 lines (55 loc) · 1.12 KB
/
Road Reparation
File metadata and controls
61 lines (55 loc) · 1.12 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
//g++ 5.4.0
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define pb push_back
#define fast ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0) ;
const int nax = 1e5+10;
int par[nax] ,sz[nax];
int fp(int v)
{
if( v==par[v] ) return v;
return par[v] = fp(par[v]);
}
struct edge_t
{
int u ,v, w;
bool operator<(edge_t const &p) const
{
return w < p.w;
}
};
vector<edge_t> e;
signed main()
{
fast;
int n , m;
cin >> n >> m;
for(int i=1 ; i<=n ; i++ ) par[i] = i , sz[i] = 1;
for(int i=0 ; i<m ; i++ )
{
int u,v,w;
cin >> u >> v >> w;
e.pb({u,v,w});
}
sort( e.begin() , e.end() );
int i=0;
int valid = 0;
int ans = 0;
while( i<m && valid< (n-1) )
{
int pu = fp(e[i].u);
int pv = fp(e[i].v);
if( pu != pv )
{
if( sz[pu] > sz[pv] ) swap(pu,pv);
par[pu] = pv;
sz[pv] += sz[pu];
ans += e[i].w;
valid++;
}
i++;
}
if( valid == n-1 ) cout << ans << "\n";
else cout << "IMPOSSIBLE";
}