Thursday, September 8, 2016

minimum spanning tree (Kruskal's algorithm) Implementation

There is an awesome kruskal algorithm tutorial  in - shafaetsplanet

here I will try to implement the algorithm in my way

a normal undirected graph

















After kruskal (MST):



















#include<bits/stdc++.h>
using namespace std;
int rep[100005];
struct edge{
int a, b , c;
}arr[100005];
bool cmp( edge x, edge y ){
return x.c < y.c;
}
void makeset(int n){
for(int i=1;i<=n;i++) rep[i]=i;
}
int findr( int x ){
if( rep[x] == x ) return x;
return rep[x] = findr( rep[x] );
}
int unio(int i,int sum){
int x,y;
x = findr( arr[i].a );
y = findr( arr[i].b );
if( x != y ){
rep[x] = y;
cout<<arr[i].a<<" "<<arr[i].b<<"\n";//connected edges
sum += arr[i].c;
}
return sum;
}
int main()
{
int n , m;
cin >> n >> m;
makeset(n);
for( int i = 0; i < m; i++ ){
int a, b, c ;
cin >> a >> b >> c;
arr[i].a = a;
arr[i].b = b;
arr[i].c = c;
}
sort( arr, arr+m , cmp );
int sum=0;
for(int i=0;i<m;i++){
sum=unio(i,sum);
}
cout << sum << "\n"; //cost
}


No comments:

Post a Comment

Football Player Transfer Prediction

Football Player Transfer Prediction Using Different Classifiers Project Report :  Football Player Transfer Prediction Report ...