Cod sursa(job #2352835)

Utilizator urweakurweak urweak Data 23 februarie 2019 18:15:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
using namespace std;

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

#define NMax 100020

int N, M;
int TT[NMax], RG[NMax];

int finds(int x)
{
    int R, y;
    for(R = x; TT[R]!=R; R = TT[R]);
    for(; 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()
{
    fin >> N >> M;
    int i, x, y, cd;
    for(int i = 1; i<=N; i++)
    {
        TT[i] = i;
        RG[i] = 1;
    }
    for(int i = 1; i<=M; i++)
    {
        fin >> cd >> x >> y;
        if(cd == 2)
        {
            if(finds(x) == finds(y)) fout <<"DA\n";
                else fout <<"NU\n";
        }
        else
        {
            unite(finds(x), finds(y));
        }
    }
}