Cod sursa(job #2847285)

Utilizator mihnea_buzoiuMihnea Buzoiu mihnea_buzoiu Data 10 februarie 2022 16:12:52
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>

using namespace std;

const int DIM = 1e5 + 2;

int to[DIM];
int siz[DIM];

int findN(int x){
    if (to[x] == x)
        return x;

    to[x] = findN(to[x]);
    return to[x];
}

void unite(int x, int y){
    x = findN(x);
    y = findN(y);

    if (siz[x] > siz[y])
        swap(x, y);

    to[x] = y;
    siz[y] += siz[x];
}


int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; i++){
        to[i] = i;
        siz[i] = 1;
    }

    for (int i=0; i<m; i++){
        int x, y, o;
        cin >> o >> x >> y;

        if (o == 1)
            unite(x, y);
        else {
            if (findN(x) == findN(y))
                cout << "DA\n";
            else cout << "NU\n";
        }

    }
}


/*
4 6
1 1 2
1 3 4
2 1 3
2 1 2
1 1 3
2 1 4
*/