File tree 1 file changed +58
-0
lines changed 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ #define int long long
4
+ #define mod (int ) (1e9 +7 );
5
+ const int N=1e5 +10 ;
6
+ int parent[N];
7
+ int sizet[N];
8
+ int n,m;
9
+ void make (int v){
10
+ parent[v]=v;
11
+ sizet[v]=1 ;
12
+ }
13
+ int find (int v){
14
+ if (parent[v]==v)return parent[v];
15
+ return parent[v]=find (parent[v]);
16
+ }
17
+ void Union (int a,int b){
18
+ a=find (a);
19
+ b=find (b);
20
+ if (a!=b){
21
+ if (sizet[a]<sizet[b]){
22
+ swap (a,b);
23
+ }
24
+ parent[b]=a;
25
+ sizet[a]+=sizet[b];
26
+ }
27
+ }
28
+ signed main () {
29
+ cin>>n>>m;
30
+ vector<pair<int ,pair<int ,int >>>vec;
31
+ for (int i=0 ;i<m;i++){
32
+ int u,v,w;
33
+ cin>>u>>v>>w;
34
+ vec.push_back ({w,{u,v}});
35
+ }
36
+ int ans=0 ;
37
+ int cnt=0 ;
38
+ for (int i=1 ;i<=n;i++)make (i);
39
+ sort (vec.begin (),vec.end ());
40
+ for (auto &it:vec){
41
+ int wt=it.first ;
42
+ int x=it.second .first ;
43
+ int y=it.second .second ;
44
+ if (find (x)==find (y))continue ;
45
+ Union (x,y);
46
+ cnt++;
47
+ ans+=wt;
48
+ }
49
+ if (cnt==n-1 ){
50
+ cout<<ans<<endl;
51
+ }
52
+ else {
53
+ cout<<" IMPOSSIBLE" <<endl;
54
+ }
55
+
56
+ return 0 ;
57
+ }
58
+
You can’t perform that action at this time.
0 commit comments