Friday 24 November 2017

C++ Program to Implement Disjoint Set Data Structure


Code:

#include   iostream
#include   cstdio
#include   vector
#include   algorithm
using namespace std;
#define INF 1000000000

typedef pair ii;
typedef vector vi;

vector > edges;
vi pset;

void init(int N)
{
    pset.assign(N, 0);
    for(int i = 0; i < N; i++)
    {
        pset[i] = i;
    }
}

int find_set(int i)
{
    if(pset[i] == i)
    {
        return pset[i];
    }
    return pset[i] = find_set(pset[i]);
}
bool issameset (int i, int j)
{
    return find_set(i) == find_set(j);
}
void joinset(int i, int j)
{
    pset[find_set(i)] = find_set(j);
}
int main()
{
    int n, m, a, b, dist, t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        init(n);
        edges.clear();
        for (int i = 0; i < m; i++)
        {
            cin>>a>>b>>dist;
            a--,b--;
            ii tmp = make_pair(a, b);
            edges.push_back(make_pair(dist, tmp));
        }
        sort(edges.rbegin(),edges.rend());
        int sum = 0;
        for(int i = 0; i < edges.size(); i++)
        {
            if (!issameset (edges[i].second.first, edges[i].second.second))
            {
               joinset(edges[i].second.first, edges[i].second.second);
            }
            else sum += edges[i].first;
        }
        cout<
    }
    cin>>t;
    getch();
}


Output:

enter the number of sets to be  computed
1
enter the number of disjoint sets and the number of rows
2
3
enter the start and end vertices alongwith weight of edge
1
1
2
enter the start and end vertices alongwith weight of edge
1
1
3
enter the start and end vertices alongwith weight of edge
1
1
4
Sum is:9



More C++ Programs:


















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...