Cod sursa(job #2651024)

Utilizator redstonegamer22Andrei Ion redstonegamer22 Data 21 septembrie 2020 14:23:57
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 100000 + 7;

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

int father[NMAX], depth[NMAX];

int get_father(int n)
{
    if(father[n] == n) return n;

    father[n] = get_father(father[n]);

    return father[n];
}

int join(int x, int y)
{
    x = get_father(x);
    y = get_father(y);
    if(x != y)
    {
        if(depth[x] > depth[y])
        {
            father[y] = x;
        }
        else if(depth[x] == depth[y])
        {
            father[y] = x;
            depth[x]++;
        }
        else
        {
            father[x] = y;
        }
    }
}

int main()
{
    int n, m; in >> n >> m;

    for(int i = 1; i <= n; i++) {father[i] = i; depth[i] = 1;}

    while(m--)
    {
        char op; int x, y; in >> op >> x >> y;
        if(op == '1')
        {
            join(x, y);
        }
        if(op == '2')
        {
            if(get_father(x) == get_father(y))
            {
                out << "DA\n";
            }
            else
            {
                out << "NU\n";
            }
        }
    }
}