-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkrushkalsalgo.cpp
65 lines (60 loc) · 896 Bytes
/
krushkalsalgo.cpp
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
#include<iostream>
#include<vector>
#include<math.h>
#include<bits/stdc++.h>
#define lli long long int
#define mod 1000000007
using namespace std;
struct edge
{
int a,b,w;
};
edge ar[100001];
int par[10001];
bool comp(edge a,edge b)
{
if(a.w<b.w)
return true;
return false;
}
int find(int a)
{
if(par[a]<0)
return a;
return par[a]=find(par[a]);
}
void Union(int a,int b)
{
par[b]=a;
}
int main()
{
ios_base::sync_with_stdio(false);
cout.tie(NULL);
int t;
cin>>t;
while(t--)
{
int i,n,m,ans=0;
cin>>n>>m;
for(i=1;i<=n;i++)
par[i]=-1 , ar[i].clear();
for(i=0;i<m;i++)
cin>>ar[i].a>>ar[i].b>>ar[i].w;
sort(ar,ar+m,comp);
for(i=0;i<m;i++)
{
int a,b;
a=find(ar[i].a);
b=find(ar[i].b);
if(a!=b)
{
ans+=ar[i].w;
Union(a,b);
cout<<endl<<ar[i].a<<" "<<ar[i].b<<endl;
}
}
cout<<ans<<"\n";
}
return 0;
}