Cod sursa(job #3042293)

Utilizator matthriscuMatt . matthriscu Data 5 aprilie 2023 14:18:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100005

int find_rep(int x, int *rep)
{
	if (rep[x] == x)
		return x;
	return rep[x] = find_rep(rep[x], rep);
}

void unite(int x, int y, int *rep, int *rank)
{
	int rep_x = find_rep(x, rep), rep_y = find_rep(y, rep);

	if (rank[rep_x] < rank[rep_y])
		rep[rep_x] = rep_y;
	else
		rep[rep_y] = rep_x;

	if (rank[rep_x] == rank[rep_y])
		++rank[rep_x];
}

int main()
{
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);

	int n, m;
	scanf("%d%d", &n, &m);

	int rep[NMAX], rank[NMAX] {};

	for (int i = 1; i <= n; ++i)
		rep[i] = i;

	for (int i = 1, code, x, y; i <= m; ++i) {
		scanf("%d%d%d", &code, &x, &y);
		if (code == 1)
			unite(x, y, rep, rank);
		else
			printf("%s\n", find_rep(x, rep) == find_rep(y, rep) ? "DA" : "NU");
	}
}