Cod sursa(job #2262327)

Utilizator Victor_InczeVictor Incze Victor_Incze Data 17 octombrie 2018 10:28:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>
#define NMAX 100005

using namespace std;

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

int TT[NMAX], RG[NMAX], n, m, x, y, t;

int find(int x)
{
    int R=x, y;
    while (TT[R]!=R)
        R=TT[R];
    while (TT[x]!=x)
    {
        y=TT[x];
        TT[x]=R;
        x=y;
    }
    return R;
}

void unite(int x, int y)
{
    if (RG[x]>RG[y])
        TT[y]=x;
    else
        TT[x]=y;
    if (RG[x]==RG[y])
        RG[y]++;
}

int main()
{
    in >> n >> m;
    for (int i=1; i<=n; i++)
        TT[i]=i, RG[i]=1;
    for (int i=1; i<=m; i++)
    {
        in >> t >> x >> y;
        if (t==2)
        {
            if (find(x)==find(y))
                out << "DA" << '\n';
            else
                out << "NU" << '\n';
        }
        else
            unite(find(x),find(y));
    }
    return 0;
}