Cod sursa(job #1243694)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 16 octombrie 2014 10:55:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>

using namespace std;

class DSU
{
public:

    DSU( const int _N )
    {
        N = _N;

        Father = vector<int>( N + 1, 0 );
        Rank = vector<int> ( N + 1, 0 );

        initialise();
    }

    void initialise()
    {
        for ( int i = 1; i <= N; ++i )
        {
            Father[i] = i;
            Rank[i] = 1;
        }
    }

    int Find( int node )
    {
        int root = node, auxNode;

        while ( Father[ root ] != root )
            root = Father[ root ];

        while ( root != Father[ node ] )
        {
            auxNode = Father[ node ];
            Father[ node ] = root;
            node = auxNode;
        }

        return root;
    }

    int Check( int x, int y )
    {
        return ( Find( x ) == Find( y ) );
    }

    void Union( int x, int y )
    {
        int fx = Find( x );
        int fy = Find( y );

        if ( fx != fy )
        {
            x = fx; y = fy;

            if ( Rank[x] < Rank[y] )
                Father[x] = y;
            else
                Father[y] = x;

            if ( Rank[x] == Rank[y] )
                Rank[y]++;
        }
    }

private:

    vector <int> Father, Rank;
    int N;
};

int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    int N, M, a, b, tip;

    in >> N >> M;

    DSU D( N );

    while ( M-- )
    {
        in >> tip >> a >> b;

        if ( tip == 1 )
        {
            D.Union( a, b );
        }
        else
        {
            if ( D.Check( a, b ) )
                out << "DA\n";
            else
                out << "NU\n";
        }
    }

    return 0;
}