Cod sursa(job #1129710)

Utilizator Impaler_009Mihai Nitu Impaler_009 Data 28 februarie 2014 08:11:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>

using namespace std;

ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");

int father[100001],depth[100001];
int n,m,x,y,op;

int parent (int x)
{
    if (father[x] != 0)
    {
       return father[x] = parent(father[x]);
    }
    return x;
}

void reunion (int x, int y)
{
    x = parent(x);
    y = parent(y);

    if (depth[x] < depth[y])
        father[x] = y;
    else
    {
        father[y] = x;
        if (depth[x] == depth[y])
           depth[x]++;
    }
}

int main()
{
    fin>>n>>m;

    for (int i=1; i<=m; ++i)
    {
        fin>>op>>x>>y;

        if (op == 1)
           reunion (x,y);
        else
        {
            if (parent(x) == parent(y))
            fout<<"DA";
            else fout<<"NU";
            fout<<"\n";
        }
    }
}