Cod sursa(job #2936279)

Utilizator CondoracheAlexandruCondorache Alexandru CondoracheAlexandru Data 8 noiembrie 2022 14:38:47
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=1e6;
int tata[maxn]={0},h[maxn]={0};

int find(int x){
    if (tata[x]!=0){
        tata[x]=find(tata[x]);
        return tata[x];
    }
    return x;
}
void Union(int x,int y){
    int r1=find(x);
    int r2=find(y);
    if (h[r1]>h[r2]){
        tata[r2]=r1;
        return;
    }
    if (h[r2]>h[r1]){
        tata[r1]=r2;
        return;
    }

    tata[r2]=r1;
    h[r1]+=1;
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    int n,m;
    fin >> n >> m;
    for(int i =1; i<=m; i++){
        int x,y,a;
        fin >> a >> x >> y;
        if(a==1){
            Union(x,y);
        }
        if(a==2){
            if(find(x)==find(y))
                fout << "DA" << endl;
            else
                fout << "NU" << endl;
        }
    }
	return 0;
}