-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathKruskal.cc
More file actions
50 lines (40 loc) · 930 Bytes
/
Copy pathKruskal.cc
File metadata and controls
50 lines (40 loc) · 930 Bytes
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
#include <cstdio>
#include <algorithm>
#define MAXN 100
using namespace std;
struct graph{
int st,en,w;
// bool operator < (const graph &g) const{
// return w<g.w;
//}
};
bool comp(graph e1, graph e2){
return e1.w<e2.w;
}
graph edge[MAXN];
int Prev[MAXN];
int parent(int a){
if(a==Prev[a]) return a;
return Prev[a]=parent(Prev[a]);
}
int main(){
int nodes,edges;
freopen("input.txt","r",stdin);
scanf("%d%d",&nodes,&edges);
int total=0;
//nodes are numbered from 0 to n-1
for(int i=0;i<nodes;i++) Prev[i]=i;
for(int i=0;i<edges;i++) scanf("%d%d%d",&edge[i].st,&edge[i].en,&edge[i].w);
sort(edge,edge+edges,comp);
for(int i=0; i<edges; i++ ){
int u=parent(edge[i].st);
int v=parent(edge[i].en);
if(u!=v){
total +=edge[i].w;
Prev[u]=v;
printf("%d %d %d\n",edge[i].st,edge[i].en,edge[i].w);
}
}
printf("Total Cost of MST is:%d\n",total);
return 0;
}