-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkruskal.cpp
91 lines (72 loc) · 1.55 KB
/
kruskal.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
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
#include<bits/stdc++.h>
using namespace std;
#define MAX 1000
#define pb push_back
int n,m,sum;
int root[MAX],weight[MAX];
struct edge{
int u,v,cost;
edge(int a, int b, int c){
u=a;
v=b;
cost=c;
}
};
struct comp{
bool operator()(const edge &first, const edge &second){
return first.cost>second.cost;
}
};
priority_queue<edge, vector< edge >, comp> pq;
///disjoint set
int find_root(int n){
if(n!=root[n])
root[n]=find_root(root[n]);
return root[n];
}
void union_set(int px, int py){
if(weight[px]>weight[py]){
root[py]=px;
weight[px]+=weight[py];
} else{
root[px]=py;
weight[py]+=weight[px];
}
}
///kruskal
void kruskal(){
int cnt=1;
for(int i=1;i<=n;i++){
root[i]=i;
weight[i]=1;
}
vector< edge > enew;
while(!pq.empty()){
edge e=pq.top();
pq.pop();
int px = find_root(e.u);
int py = find_root(e.v);
if(px!=py){
enew.pb(e);
sum+=e.cost;
union_set(px,py);
cnt++;
if(cnt==n) break;
}
}
for(int i=0;i<enew.size();i++){
cout<<enew[i].u<<" "<<enew[i].v<<" "<<enew[i].cost<<endl;
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v,cost;
cin>>u>>v>>cost;
pq.push(edge(u,v,cost));
}
sum=0;
kruskal();
cout<<"Total Cost: "<<sum<<endl;
return 0;
}