Cod sursa(job #2646604)

Utilizator DormeoNoapte Buna Dormeo Data 1 septembrie 2020 15:58:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;

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

const int DIM = 100000 + 5;

int Size[DIM], parent[DIM];

void make_set(int k)
{
    Size[k] = 1;
    parent[k] = k;
}

int find_set(int k)
{
    if(parent[k] == k) return k;
    return parent[k] = find_set(parent[k]);
}

void union_sets(int a, int b)
{
    a = find_set(a);
    b = find_set(b);
    if(a != b) {
        if(Size[b] > Size[a]) {
            swap(a, b);
        }
        Size[a] += Size[b];
        parent[b] = a;
    }
}

int main()
{
    int n, m;

    fin >> n >> m;
    for(int i = 1; i <= n; ++i) make_set(i);
    for(int i = 1; i <= m; ++i) {
        int type, x, y;

        fin >> type >> x >> y;
        if(type == 1) union_sets(x, y);
        else if(type == 2) {
            if(find_set(x) == find_set(y)) fout << "DA" << "\n";
            else fout << "NU" << "\n";
        }
    }
    return 0;
}