Cod sursa(job #3264950)

Utilizator Manolea_Teodor_StefanManolea Teodor Stefan Manolea_Teodor_Stefan Data 25 decembrie 2024 22:30:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")

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

int n,m;
vector<int> t;

int getRoot(int node) {
    while (t[node] > 0) {
        node = t[node];
    }
    return node;
}

void connect(int a, int b) {
    const int rootA = getRoot(a);
    const int rootB = getRoot(b);
    if (t[rootA] > t[rootB]) {
        t[rootB] += t[rootA];
        t[rootA] = rootB;
        while (a != rootA) {
            const int x = t[a];
            t[a] = rootB;
            a = x;
        }
    } else {
        t[rootA] += t[rootB];
        t[rootB] = rootA;
        while (b != rootB) {
            const int x = t[b];
            t[b] = rootA;
            b = x;
        }
    }
}
const string ans[] = {"NU\n","DA\n"};
int main() {
    fin >> n >> m;
    t.assign(n+1,-1);
    while (m--) {
        int q,a,b;
        fin >> q >> a >> b;
        if (q == 1) {
            connect(a,b);
        } else {
            fout << ans[getRoot(a) == getRoot(b)];
        }
    }
    return 0;
}