Cod sursa(job #1688807)

Utilizator tudormaximTudor Maxim tudormaxim Data 13 aprilie 2016 18:59:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.76 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");

const int nmax = 1e5+5;
int dady[nmax], rang[nmax];

inline int Find(int x) {
    while(x!=dady[x]) x=dady[x];
    return x;
}

inline void Union(int x, int y) {
    if(rang[x] > rang[y]) dady[y]=x;
    else dady[x]=y;
    if(rang[x]==rang[y]) rang[y]++;
}

int main() {
    ios_base::sync_with_stdio(false);
    int n, m, i, x, y;
    fin >> n >> m;
    for(i=1; i<=n; i++)
        dady[i]=i;
    while(m--) {
        fin >> i >> x >> y;
        if(i==1) Union(Find(x), Find(y));
        else if(Find(x)==Find(y)) fout << "DA\n";
        else fout << "NU\n";
    }
    fin.close();
    fout.close();
    return 0;
}