Cod sursa(job #2196831)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 20 aprilie 2018 15:10:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.79 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

struct Node{
    int rnk, dad;
}a[100002];
int n, m;

int rad(int nod)
{
    int init=nod, x=a[nod].dad;
    while(nod!=x)
    {
        nod=x;
        x=a[x].dad;
    }
    a[init].dad=x; ///path compression
    return x;
}

void join(int x, int y)
{
    int xx=rad(x), yy=rad(y);
    if(a[xx].rnk==a[yy].rnk) a[xx].dad=yy, a[yy].rnk++;
    else if(a[xx].rnk<a[yy].rnk) a[xx].dad=yy;
    else a[yy].dad=xx;
}

int main()
{
    int i, cod, x, y;
    fin>>n>>m;
    for(i=1; i<=n; i++) a[i].dad=i;
    for(i=1; i<=m; i++)
    {
        fin>>cod>>x>>y;
        if(cod==1) join(x,y);
        else fout<<((rad(x)==rad(y)) ? "DA" : "NU")<<'\n';
    }
    return 0;
}