Cod sursa(job #2612075)

Utilizator Horia14Horia Banciu Horia14 Data 8 mai 2020 14:28:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include<fstream>
#include<iostream>
#define MAX_N 100000
using namespace std;

int p[MAX_N + 1], h[MAX_N + 1], n, m;

void Init(int n) {
    for(int i = 1; i <= n; i++) {
        p[i] = i;
        h[i] = 1;
    }
}

int Find(int x) {
    int r, aux;
    r = x;
    while(r != p[r])
        r = p[r];
    while(p[x] != r) {
        aux = p[x];
        p[x] = r;
        x = aux;
    }
    return r;
}

void Union(int x, int y) {
    int rootx, rooty;
    rootx = Find(x);
    rooty = Find(y);
    if(h[rootx] < h[rooty])
        p[rootx] = rooty;
    else if(h[rootx] > h[rooty])
        p[rooty] = rootx;
    else {
        p[rootx] = rooty;
        h[rooty]++;
    }
}

int main() {
    int n, m, op, x, y;
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    fin >> n >> m;
    Init(n);
    for(int i = 1; i <= m; i++) {
        fin >> op >> x >> y;
        //cout << op << " " << x << " " << y << "\n";
        if(op == 1)
            Union(x, y);
        else {
            if(Find(x) == Find(y))
                fout << "DA\n";
            else fout << "NU\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}