Cod sursa(job #2427369)

Utilizator teoschipor00Teodora Schipor teoschipor00 Data 31 mai 2019 17:27:05
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#define Nmax 100005
using namespace std;

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

int tata[Nmax], grad[Nmax];

int FindFather(int nod)
{
    if(tata[nod] == nod)
        return nod;
    tata[nod] = FindFather(tata[nod]);
    return tata[nod];
}

void connect(int x, int y)
{
    if(grad[x] < grad[y])
    {
        tata[x] = y;
        grad[y] += grad[x];
    }
    else
    {
        tata[y] = x;
        grad[x] += grad[y];
    }
}


int main()
{
    int n, m;
    f >> n >> m;
    for(int i = 1; i <= n; i ++)
    {
        grad[i] = 1;
        tata[i] = i;
    }
    for(int i = 0; i < m; i ++)
    {
        int cod, x, y;
        f >> cod >> x >> y;
        int fx = FindFather(x);
        int fy = FindFather(y);
        if(cod == 2)
        {
            if(fx == fy)
                g << "DA" << endl;
            else
                g << "NU" << endl;
        }
        else
            connect(fx, fy);
    }
    return 0;
}