Cod sursa(job #2895276)

Utilizator matthriscuMatt . matthriscu Data 28 aprilie 2022 21:07:11
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 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[x] < rank[y]) {
		rep[x] = rep_y;
		rank[x] = ++rank[y];
	} else {
		rep[y] = rep_x;
		rank[y] = ++rank[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");
	}
}