Cod sursa(job #2571929)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 5 martie 2020 10:51:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;

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

const int N_MAX = 1e5 + 1;

int parent[N_MAX], tree_size[N_MAX];


int find_root(int node)
{
    int aux = node;

    while(parent[aux] != 0)
    {
        aux = parent[aux];
    }

    int root = aux;

    while(node != root)
    {
        aux = parent[node];
        parent[node] = root;
        node = aux;
    }

    return root;
}

void combine_trees(int node_x, int node_y)
{
    int root_x = find_root(node_x);
    int root_y = find_root(node_y);

    if(root_x == root_y) return;

    if(tree_size[root_x] < tree_size[root_y]) swap(root_x, root_y);

    tree_size[root_x] += tree_size[root_y];
    parent[root_y] = root_x;
}


int main()
{
    int N, M;
    fin >> N >> M;

    for(int x, y, c, i = 1; i <= M; ++i)
    {
        fin >> c >> x >> y;

        if(c == 1)
        {
            combine_trees(x, y);
        }
        else
        {
            if(find_root(x) == find_root(y))
            {
                fout << "DA\n";
            }
            else
            {
                fout << "NU\n";
            }
        }
    }
}