Cod sursa(job #2216376)

Utilizator PopeangaMihneaPopeanga Mihnea- Stefan PopeangaMihnea Data 26 iunie 2018 15:24:23
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>

using namespace std;

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

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

int root(int x)
{
    int R=x, y;
    while(father[R]!=R) R=father[R];
    while(father[x]!=x)
    {
        y=father[x];
        father[x]=R;
        x=y;
    }
    return R;
}

void unite(int x, int y)
{
    if(grade[x]>grade[y]) father[y]=x;
    else father[x]=y;
    if(grade[x]==grade[y]) ++grade[y];
}

int main()
{
    fin>>n>>m;
    for(int i=1; i<=n; ++i)
    {
        father[i]=i;
        grade[i]=1;
    }
    for(int i=1; i<=m; ++i)
    {
        fin>>op>>x>>y;
        if(op==1)
        {
            unite(root(x), root(y));
        }
        else
        {
            if(root(x)==root(y)) fout<<"DA\n";
            else fout<<"NU\n";
        }
    }
    return 0;
}