Cod sursa(job #2837392)

Utilizator IoncioaiaCalinIoncioaia Calin IoncioaiaCalin Data 22 ianuarie 2022 10:21:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;
#if true
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
#else
#define fin cin
#define fout cout
#endif

int n,q;
int tata[100005];

int getRoot(int node, int& height)
{
    int startNode = node;

    height = 0;
    int parent;
    while (node != 0)
    {
        parent = tata[node];
        if (parent == 0) break;
        node = parent;
        height++;
    }

    if (height > 0)
        tata[startNode] = node;

    return node;
}

int main()
{
    ios_base::sync_with_stdio(false);
    
    fin >> n >> q;
    int type, x, y;
    for (int qi=1; qi<=q;qi++)
    {
        fin >> type >> x >> y;

        int heightX=0, heightY=0;
        int rootX = getRoot(x,heightX);
        int rootY = getRoot(y,heightY);

        if (type == 1)
        {
            if (rootX != 0 && rootX == rootY) continue;

            if (heightX<heightY)
                tata[rootX] = rootY;
            else
                tata[rootY] = rootX;

            continue;
        }

        if (rootX != x)
            tata[x] = rootX;
        if (rootY != y)
            tata[y] = rootY;

        fout << ((rootX != 0 && rootX == rootY)? "DA\n" : "NU\n"); 
    }

    return 0;
}