Cod sursa(job #2295489)

Utilizator LucianTLucian Trepteanu LucianT Data 3 decembrie 2018 18:18:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
using namespace std;

const int maxN=1e5+1;

int n,q;

int t[maxN];
int sz[maxN];

int findDSU(int x){
    if(t[x]!=x)
        return t[x]=findDSU(t[x]);
    return t[x];
}

void uniteDSU(int x,int y){
    int tx=findDSU(x);
    int ty=findDSU(y);

    if(tx==ty)
        return;

    if(sz[tx]<sz[ty]){
        t[tx]=ty;
        sz[ty]+=sz[tx];
    } else {
        t[ty]=tx;
        sz[tx]+=sz[ty];
    }
}

int main(){
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");

    cin>>n>>q;
    for(int i=1;i<=n;i++){
        t[i]=i;
        sz[i]=1;
    }

    while(q--){
        int op,x,y;
        cin>>op>>x>>y;

        if(op==1)
            uniteDSU(x,y);
        else{
            if(findDSU(x)==findDSU(y))
                cout<<"DA"<<'\n';
            else cout<<"NU"<<'\n';
        }
    }

    return 0;
}