Cod sursa(job #2640445)

Utilizator BereaBerendea Andrei Berea Data 6 august 2020 14:36:19
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>

using namespace std;
int tip,x,y;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
const int MAXN = 1e6 + 5;
int t[MAXN],n,m,h[MAXN];

int findroot(int nod) {
	if(t[nod] == nod)
		return nod;
	return t[nod] = findroot(t[nod]);
}

void Union(int rad1, int rad2) {
	if(h[rad1] > h[rad2]) {
		t[rad2] = rad1;
}
else
	if(h[rad1] < h[rad2]) {
		t[rad1] = rad2;
}
else // daca au aceeasi inaltime
{
	t[rad1] = rad2;
	h[rad2]++;
}

}

int main() {
	fin >> n >> m;
	for (int i = 1; i <= n; ++i) {
		t[i] = i;
		h[i] = 1;
}
	for ( int i =1 ;i <= m; ++i) {
	fin >> tip >> x >> y;
	if(tip == 1) {
	if(findroot(x) != findroot(y)){
		Union(findroot(x),findroot(y));
}
	else
	{
		if(findroot(x) == findroot(y))
	fout <<"DA\n";
else
	fout <<"NU\n";
}
}
}
}