Cod sursa(job #2491799)

Utilizator RaduNRadu Negovan RaduN Data 13 noiembrie 2019 10:02:11
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int finder (int x){
    while (x!=t[x]){
        x=t[x];
    }
    return x;
}
void uniter (int x, int y){
    if (h[x]==h[y]){
        t[y]=x;
        h[y]++;
    }
    else{
        if (h[x]>h[y]){
            t[y]=x;
        } else {
            t[x]=y;
        }
    }
}
int n, m, x, y, c, tx, ty, t[100002], h[100002];
int main() {
    f>>n>>m;
    for (int i=1; i<=n; i++){
        h[i]=1;
        t[i]=i;
    }
    for (int i=1; i<=m; i++){
        f>>c>>x>>y;
        tx=finder(x);
        ty=finder(y);
        if (c==1 && tx!=ty){
            uniter(tx, ty);
        }
        if (c==2){
            if (tx==ty){
                g<<"DA";
            } else {
                g<<"NU";
            }
        }
    }
    return 0;
}