Cod sursa(job #2862858)

Utilizator Andrei_Tud1Andrei Tudorache Andrei_Tud1 Data 5 martie 2022 22:32:14
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <stdio.h>
#define MAXN 100005

using namespace std;
int t[MAXN], n;

int get_root(int x)
{
    int nod = x, aux;
    while(t[x] > 0)
        x = t[x];

    while(nod != x)
    {
        aux = t[nod];
        t[nod] = x;
        nod = aux;
    }
    return x;
}

void join(int x, int y)
{
    int rootX = get_root(x), rootY = get_root(y);

    if(rootX == rootY)
        return;

    if(t[rootX] < t[rootY])
    {
        t[rootX] += t[rootY];
        t[rootY] = rootX;
    }
    else
    {
        t[rootY] += t[rootX];
        t[rootX] = rootY;
    }
}

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int main()
{
    int i, m, op, x, y;
    fin >> n >> m;
    for(i = 1; i <= n; i++)
        t[i] = -1;
    for(i = 1; i <= m; i++)
    {
        fin >> op >> x >> y;
        if(op == 1)
        {
            join(x, y);
        }
        else
        {
            if(get_root(x) == get_root(y))
                fout << "DA" << endl;
            else
                fout << "NU" << endl;
        }
    }
    fin.close(); fout.close();
    return 0;
}