Saturday, February 18, 2017

Kruskal's Algorithm - Implementation with C++

/*
  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;
}

No comments:

Post a Comment