Cod sursa(job #2228646)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 4 august 2018 15:16:28
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>
using namespace std;
int n, m, i, c, x, y, p[100005], r[100005], xroot, yroot;
int findroot(int x)
{
    if(p[x] != x)findroot(p[x]);
    else return x;
}
void unite(int x, int y)
{
    xroot = findroot(x);
    yroot = findroot(y);
    if(xroot != yroot)
    {
        if(r[xroot] < r[yroot])
        {
            p[xroot] = yroot;
            r[xroot]++;
        }
        else
        {
            p[yroot] = xroot;
            r[yroot]++;
        }
    }
}
int main()
{
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    f >> n >> m;
    for(i = 1;i <= n;i++)
    {
        p[i] = i;
        r[i] = 1;
    }
    for(i = 1;i <= m;i++)
    {
        f >> c >> x >> y;
        if(c == 1)unite(x, y);
        else if(findroot(x) == findroot(y))g << "DA" << "\n";
        else g << "NU" << "\n";
    }
    return 0;
}