Cod sursa(job #2763641)

Utilizator LXGALXGA a LXGA Data 15 iulie 2021 17:05:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int n, m;
int c, x, y;
int r[100001], h[100001];
int f(int nod)
{
	int x = nod;
	while (r[x] != 0)
		x = r[x];
	while (r[nod] != 0)
	{
		int aux = r[nod];
		r[nod] = x;
		nod = aux;
	}
	return x;
}
void u(int x, int y)
{
	x = f(x);
	y = f(y);
	if (h[x] < h[y])
		r[x] = y;
	else if (h[x] > h[y])
		r[y] = x;
	else
	{
		r[x] = y;
		h[y]++;
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		cin >> c >> x >> y;
		if (c == 2)
		{
			if (f(x) == f(y))
				cout << "DA\n";
			else cout << "NU\n";
		}
		else
		{
			u(x, y);
		}
	}
	return 0;
}