Cod sursa(job #1435209)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 12 mai 2015 14:26:35
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<fstream> // Paduri de multimi disjuncte (DSU) Disjoint O(log star n) aprox O(1).
#define NMAX 100020
using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

int root[NMAX];
int rang[NMAX];
int i,n,t;

int find(int x)
{
    int r, aux;
    
    for(r=x; root[r]!=r; r=root[r]);
    
    while(root[x]!=x) // compresia drumurilor // euristica(II)
    {
        aux=root[x]; // the parent of the current node
        root[x]=r; // set the parent of the current node equal to the root found
        x=aux; // move up and set parents equal to the root found till the root is reached
    }
    return r;
}

void unite(int x, int y)
{
    if(rang[x] < rang[y]) // radacina cu rang mai mic lipim la cea mai mare (euristica I)// rang mai mic la rang mai mare
        root[x] = y;
    else
        root[y] = x;
    
    if(rang[x] == rang[y]) rang[x]++;
}

int main()
{
    cin>>n>>t;
    
    for(i=1; i<=n; ++i)
    {
        rang[i]=1;
        root[i]=i;
    }
    
    while(t--)
    {
        int c,x,y;
        cin>>c>>x>>y;
        
        if(c==1){
            if(find(x) == find(y)) t=t;
            unite(find(x), find(y));
        }
        else
            if(find(x)==find(y))
                cout<<"DA"<<endl;
            else
                cout<<"NU"<<endl;
    }
    return 0;
}