Cod sursa(job #1217036)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 6 august 2014 15:01:45
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>

using namespace std;

class DSU
{
public:

    DSU() {}

    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, auxNode;

        for ( root = node; Father[ root ] != root; root = Father[ root ] );

        while ( node != 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 )
    {
        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 N, M;

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

    in >> N >> M;

    DSU D( N );

    for ( int i = 1, tip, x, y; i <= M; ++i )
    {
        in >> tip >> x >> y;

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

    return 0;
}