Cod sursa(job #2797997)

Utilizator Cezar211Popoveniuc Cezar Cezar211 Data 10 noiembrie 2021 20:11:36
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <bits/stdc++.h>
#define NMAX 100005
using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int N, Q;
int t[NMAX];
// 1 2 3 4 5 6 7 8 9
// 1 1 2 2 1 6 6 6 7
int find(int nod) {
    if(t[nod] == nod)
        return nod;
    return (t[nod] = find(t[nod]));
}
void unite(int nod1, int nod2) {
    // O(N)
    int r1 = find(nod1);
    int r2 = find(nod2);
    t[r2] = r1;
}
int main() {
    fin >> N >> Q;
    for(int i=1; i<=N; i++)
        t[i] = i;
    while(Q--) {
        int P, x, y;
        fin >> P >> x >> y;
        if(P == 1)
            unite(x, y);
        else {
            if(find(x) == find(y))
                fout << "DA\n";
            else fout << "NU\n";
        }

    }

    return 0;
}