Cod sursa(job #2525977)

Utilizator AlexBolfaAlex Bolfa AlexBolfa Data 18 ianuarie 2020 09:54:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
#define NMAX (int)(1e5+4)
#define pb emplace_back
#define ft first
#define sd second
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
typedef pair <int, int> pairINT;
typedef long long ll;

int n,q,depth[NMAX],urm[NMAX];
int ufind(int);
void umerge(int,int);

int main(){
    fin>>n>>q;
    for(int type,x,y;q;--q){
        fin>>type>>x>>y;
        x=ufind(x); y=ufind(y);
        if(type == 1){
            if(depth[x] > depth[y])
                umerge(x, y);
            else{
                umerge(y, x);
            }
        }else fout<<(x == y ? "DA\n":"NU\n");
    }
    return 0;
}
int ufind(int node){
    int temp=node,root;
    while(urm[node])
        node=urm[node];
    root=node;
    node=temp;
    while(urm[node])
        temp=urm[node],
        urm[node]=root,
        node=temp;

    return root;
}
void umerge(int x,int y){//x <- y
    urm[y]=x;
    depth[x]=max(depth[x], depth[y]+1);
}