Cod sursa(job #2494534)

Utilizator AndreiAlexandru2k3Ciucan Andrei Alexandru AndreiAlexandru2k3 Data 18 noiembrie 2019 00:33:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int NMAX=100001;

int T[NMAX],RG[NMAX];
int N,M;

int gasit(int x)
{
	int R, y;
	for (R = x; T[R] != R; R = T[R]);
	for (; T[x] != x;)
	{
		y = T[x];
		T[x] = R;
		x = y;
	}
	return R;
}

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

int main()
{
    f>>N>>M;
    for(int i=1;i<=N;i++){
        T[i]=i;
        RG[i]=1;
    }
    int cod,x,y;
    for(int i=1;i<=M;i++){
        f>>cod>>x>>y;
        if(cod==1)
            unire(gasit(x),gasit(y));
        else
        {
            if(gasit(x)==gasit(y)) g<<"DA\n";
            else g<<"NU\n";
        }
    }
    return 0;
}