Cod sursa(job #2515274)

Utilizator blotucosmincosmin blotucosmin Data 28 decembrie 2019 11:47:28
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
using namespace std;
int tata[100001], rg[100001], n, m, t, x, y, px, py;
int findroot(int x)
{
    while(tata[x] != x) x = tata[x];
    return tata[x];
}
void Union(int x, int y)
{
    px = findroot(x);
    py = findroot(y);
    if(px != py)
    {
        if(tata[px] < tata[py])
        {
            tata[px] = py;
            rg[px] ++;
        }
        else
        {
            tata[py] = px;
            rg[py] ++;
        }
    }
}
int main()
{
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    f >> n >> m;
    for(int i = 1; i <= n; ++ i)
    {
        tata[i] = i;
        rg[i] = 1;
    }
    for(int i = 1; i <= m; ++ i)
    {
        f >> t >> x >> y;
        if(t == 1) Union(x, y);
        else if(findroot(x) == findroot(y)) g << "DA" << "\n";
        else g << "NU" << "\n";
    }
    return 0;
}