Cod sursa(job #2649157)

Utilizator OvidRata Ovidiu Ovid Data 13 septembrie 2020 11:01:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include<bits/stdc++.h>
using namespace std;
#define INIT  ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define mp make_pair
#define pb push_back
#define ft first
#define sc second
#define ll long long
#define pii pair<int, int>
#define count_bits __builtin_popcount
#define int ll

ifstream fin("disjoint.in"); ofstream fout("disjoint.out");
#define cin fin
#define cout fout
int t, n, m, k, a[300010], q, l, r;
int ptr[100010];
int rnk[100010];

int find_root(int x){

int cr=x;
vector<int> forests;
while(ptr[cr]!=cr){
    forests.pb(cr);
    cr=ptr[cr];
}
int mx=0;
for(int i=0; i<forests.size(); i++){
    ptr[forests[i] ]=cr;
    mx=max(rnk[forests[i] ]+1, mx);
}
rnk[cr]=mx;

return cr;
}



void disjoint_union(int x, int y){
int r1=find_root(x), h1=rnk[r1];
int r2=find_root(y), h2=rnk[r2];
if(h2<h1){
    ptr[r2]=r1;
    rnk[r1]=max(rnk[r1], rnk[r2]+1);
}
else{
    ptr[r1]=r2;
    rnk[r2]=max(rnk[r2], rnk[r1]+1);
}
return;
}



bool same_set(int x, int y){
int r1=find_root(x);
int r2=find_root(y);
if(r1==r2){
    return true;
}
else{
    return false;
}
}


int32_t main(){
INIT
cin>>n>>m;
for(int i=1;i<=n; i++){ptr[i]=i;}
while(m--){

int o, x, y;
cin>>o>>x>>y;
if(o==1){
    disjoint_union(x, y);
}
else{
    if(same_set(x, y)==true){
        cout<<"DA\n";
    }
    else{
        cout<<"NU\n";
    }
}

}



return 0;
}