Cod sursa(job #2838882)

Utilizator Andrei_Tud1Andrei Tudorache Andrei_Tud1 Data 24 ianuarie 2022 20:37:17
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#define MAXN 100005

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int t[MAXN];
int root(int node)
{
    int x = node;
    while(t[node] > 0)
        node = t[node];

    while(t[x] > 0)
    {
        int aux = t[x];
        t[x] = node;
        x = aux;
    }
    return node;
}

void join(int a, int b)
{
    int rootA = root(a), rootB = root(b);

    /*if(rootA == rootB)
        return;*/

    if(t[rootA] <= t[rootB])
    {
        t[rootA] += t[rootB];
        t[rootB] = rootA;
    }
    else
    {
        t[rootB] += t[rootA];
        t[rootA] = rootB;
    }
}

int main()
{
    int n, m, op, a, b;
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
        t[i] = -1;
    for(int i = 1; i <= m; i++)
    {
        fin >> op >> a >> b;
        if(op == 1)
            join(a, b);
        else
        {
            if(root(a) == root(b))
                fout << "DA" << endl;
            else
                fout << "NU" << endl;
        }
    }
    fin.close(); fout.close();
    return 0;
}