Cod sursa(job #2080211)

Utilizator xkz01X.K.Z. xkz01 Data 2 decembrie 2017 16:17:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include<cstdio>
using namespace std;
int i, n, m, tt[100005], grad[100005], op, x, y;
inline int find(int y){
    int aux, cine=y;
    while (tt[cine]!=cine) cine=tt[cine];
    while (tt[y]!=y) {aux=tt[y]; tt[y]=cine; y=aux;}
    return cine;
}
inline void unite(int x, int y){
    if (grad[x]>grad[y]) tt[x]=y; else tt[y]=x;
    if (grad[x]==grad[y]) grad[x]++;
}
int main(){
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);
    scanf("%d%d", &n, &m);
    for (i=1;i<=n;i++) {tt[i]=i; grad[i]=1;}
    for (i=1;i<=m;i++) {
        scanf("%d%d%d", &op, &x, &y);
        if (op==1) unite(find(x),find(y));
        if (op==2) {if (find(x)==find(y)) printf("DA\n"); else printf("NU\n");}
    }
    return 0;
}