Cod sursa(job #2914952)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 21 iulie 2022 14:12:50
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, q;
int m[100005];
int sz[100005];

int Find(int x) {
    int root = x;

    while(m[root] != root) {
        root = m[root];
    }

    while(m[x] != x) {
        int copie = m[x];

        m[x] = root;
        x = copie;
    }

    return root;
}

void Union(int x, int y) {
    int rootX = Find(x);
    int rootY = Find(y);

    // se lipeste multimea cu reprezentantul rootY la rootX
    if(sz[rootX] > sz[rootY]) {
        sz[rootX] += sz[rootY];
        m[rootY] = rootX;
    }
    // invers
    else {
        sz[rootY] += sz[rootX];
        m[rootX] = rootY;
    }
}

int main()
{
    fin >> n >> q;

    for(int i = 1; i <= n; i++) {
        m[i] = i;
        sz[i] = 1;
    }

    int tip, a, b;
    for(int i = 1; i <= q; i++) {
        fin >> tip >> a >> b;

        if(tip == 1)
            Union(a, b);
        else {
            if(Find(a) == Find(b))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

    return 0;
}