Cod sursa(job #2946464)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 24 noiembrie 2022 21:29:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
#define cin f
#define cout g
const int Max = 1e5 + 1;

int parent[Max], Rank[Max];

void make_set(int x)
{
	parent[x] = x;
	Rank[x] = 0;
}

int find_set(int x)
{
	if(x == parent[x])
		return x;
	return parent[x] = find_set(parent[x]);
}

void union_sets(int x, int y)
{
	x = find_set(x);
	y = find_set(y);

	if(x != y)
	{
		if(Rank[x] < Rank[y])
			swap(x, y);
		parent[y] = x;
		if(Rank[x] == Rank[y])
			Rank[x] ++;
	}
}

int main()
{
	int n, m;
	cin >> n >> m;

	for(int i = 1; i <= n; i ++)
		make_set(i);

	for(int i = 1; i <= m; i ++)
	{
		int op, x, y;
		cin >> op >> x >> y;
		if(op == 1)
			union_sets(x, y);
		else
		{
			if(find_set(x) == find_set(y))
				cout<<"DA\n";
			else
				cout<<"NU\n";
		}
	}
	return 0;
}