Cod sursa(job #2754449)

Utilizator MohneaGosuMihnea Gusu MohneaGosu Data 25 mai 2021 21:01:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>

using namespace std;
ifstream cin ("disjoint.in");
ofstream cout ("disjoint.out");
const int n1=100001;
int t[n1];
int s[n1];
void unire(int x,int y)
{
    if (s[x]<s[y]) t[x]=y;
    else if(s[x]>s[y]) t[y]=x;
    else{
        t[y]=x;
        s[x]++;
    }
}
int gasire(int x)
{
    while(x!=t[x]){
        x=t[x];
    }
    return x;
}
int main()
{
    int n,m,i,f,x,y;
    cin>>n>>m;
    for (i=1;i<=n;i++){
        t[i]=i;
    }
    for (i=0;i<m;i++){
        cin>>f;
        cin>>x>>y;
        if (f==1){
            x=gasire(x);
            y=gasire(y);
            unire(x,y);
        }
        else{
            x=gasire(x);
            y=gasire(y);
            if (x==y) cout<<"DA\n";
            else cout<<"NU\n";
        }
    }
    return 0;
}