/*
Bismillahir Rahmanir Rahim
Implementation of (MST)Kruskal's algorithm with C++
*/
#include<bits/stdc++.h>
#define fi(i, n) for(int i=0; i<n; i++)
using namespace std;
struct node{ // structure
int u, v, cost;
};
int pr[101], edge, n;
node one[100];
bool comp(node f, node s){ // sort of structure
return f.cost<s.cost;
}
int find(int p){ // Disjoint Set
if(pr[p]==p)return p;
else return find(pr[p]);
}
int mst(int st){ // minimum-cost spanning tree
fi(i, n) pr[i]=i;
int cnt=0, xx, sm=0, yy;
fi(i, edge){
xx=find(one[i].u); // parent of one[i].u
yy=find(one[i].v);
if(xx!=yy){
pr[yy]=xx;
cnt++;
sm+=one[i].cost;
}
if(cnt==n-1) break;
}
return sm;
}
int main(){
int u, v, cost;
/* input start */
cin>>n>>edge;
fi(i, edge){
cin>>u>>v>>cost;
one[i].u=u;
one[i].v=v;
one[i].cost=cost;
}
sort(one, one+edge, comp);
cout<<mst(1)<<endl;
return 0;
}
|
Saturday, February 18, 2017
Kruskal's Algorithm - Implementation with C++
Subscribe to:
Post Comments (Atom)
-
#include<bits/stdc++.h> #define ll long long using namespace std ; ll n , k , t_case ; ll bigmod ( ll b , ll p , ll m...
-
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 ...
-
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 3...
No comments:
Post a Comment