Cod sursa(job #3201725)

Utilizator laurentiu.maticaMatica Laurentiu-Andrei laurentiu.matica Data 9 februarie 2024 17:42:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
const int nmax = 100000;
const int mmax = 100000;
int n, m;
int t[nmax + 1];
int rang[nmax + 1];
int radacina(int k)
{
	if (!t[k])
		return k;
	else
	{
		int x = radacina(t[k]);
		t[k] = x;
		return x;
	}
}
void unire(int k, int p)
{
	int rk = radacina(k);
	int rp = radacina(p);
	if (rp != rk)
	{
		if (rang[rp] > rang[rk])
			t[rp] = rk;
		else
		{
			t[rk] = rp;
			if (rang[rp] == rang[rk])
				rang[rp]++;
		}
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		t[i] = 0;
		rang[i] = 1;
	}
	for (int i = 0; i < m; i++)
	{
		int cd, x, y;
		cin >> cd >> x >> y;
		if (cd == 2)
		{
			if (radacina(x) == radacina(y))
				cout << "DA" << '\n';
			else
				cout << "NU" << '\n';
		}
		else
		{
			if (radacina(x) == radacina(y))
				return 0;
			unire(x, y);
		}
	}
	return 0;
}