Cod sursa(job #2460473)

Utilizator bogdan2604Bogdan Dumitrescu bogdan2604 Data 23 septembrie 2019 19:29:38
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,i,tip,x,y,xroot,yroot,tata[100001],Rank[100001];;

int cauta(int x)
{
    if(tata[x] != x)
        tata[x] = cauta(tata[x]);
    return tata[x];
}
void Union(int x,int y)
{
    if(Rank[x] > Rank[y])
        tata[y] = x;
    else if(Rank[x] < Rank[y])
        tata[x] = y;
    else
    {
        tata[y] = x;
        ++ Rank[x];
    }
}
int main()
{
    ios::sync_with_stdio(0);
    f >> n >> m;
    for(i = 1; i <= n; ++ i)
    {
        tata[i] = i;
        Rank[i] = 0;
    }

    while(m --)
    {
        f >> tip >> x >> y;
        xroot = cauta(x);
        yroot = cauta(y);
        if(tip == 1)
        {
            if(x != y)
                Union(x,y);
        }
        else
            xroot == yroot ? g << "DA\n" : g << "NU\n";
    }
}