Cod sursa(job #882572)

Utilizator DEYDEY2Tudorica Andrei DEYDEY2 Data 19 februarie 2013 11:06:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
using namespace std;
ifstream fi("disjoint.in");
ofstream fo("disjoint.out");
int N,Q,i,tip;
int v1,v2;
int P[100001];
int NRV[100001];
int strv1,strv2;

// functia f returneaza stramosul unui varf, v
int f(int v)
{
    while (P[v]!=0)
        v=P[v];
    return v;
}

int main()
{
    fi>>N>>Q;
    for (i=1;i<=N;i++)
        NRV[i]=1;
    for (i=1;i<=Q;i++)
    {
        fi>>tip;
        if (tip==1)
        {
            fi>>v1>>v2;
            strv1=f(v1);
            strv2=f(v2);
            if (NRV[strv1]<=NRV[strv2])
            {

                P[strv1]=strv2;
                NRV[strv2]+=NRV[strv1];
            }
            else
            {
                P[strv2]=strv1;
                NRV[strv1]+=NRV[strv2];
            }
        }
        else
        {
            fi>>v1>>v2;
            strv1=f(v1);
            strv2=f(v2);
            if (strv1==strv2)
                fo<<"DA\n";
            else
                fo<<"NU\n";
        }
    }
    fi.close();
    fo.close();
    return 0;
}