Cod sursa(job #3306028)

Utilizator Botnaru_VictorBotnaru Victor Botnaru_Victor Data 6 august 2025 19:47:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
using namespace std;
//#define TESTS

#define x first
#define y second
#define pii pair<int,int>
#define veci vector<int>
#define vecp vector<pii>
#define all(x) x.begin(), x.end()
#define pb(x,y) x.push_back(y)

const int maxn = 1e5+5;

int n,m,tata[maxn], h[maxn];

//returneaza reprezentatul multimii lui x (adica radacina componentei)
int get_root(int x)
{
	if(x==tata[x]) return x;
	return tata[x] = get_root(tata[x]);
}

bool in_same_component(int x, int y)
{
	return get_root(x) == get_root(y);
}

void join(int x, int y)
{
	x = get_root(x);
	y = get_root(y);

	if(x==y) return;
	
	if(h[x]<h[y]) swap(x,y);
	if(h[x]==h[y]) h[x]++;

	tata[y]=x;
}


void solve()
{
	cin>>n>>m;

	for(int i=1;i<=n;i++)
	{
		tata[i]=i;
		h[i]=1;
	}

	int c,x,y;
	for(int i=1;i<=m;i++)
	{
		cin>>c>>x>>y;

		if(c==1)
		{
			join(x,y);
		}
		else
		{
			if(in_same_component(x,y)) cout<<"DA\n";
			else cout<<"NU\n";
		}
	}
}

int main()
{
	#ifndef LOCAL
		#define fname "disjoint"
		freopen(fname".in","r", stdin);
		freopen(fname".out","w",stdout);
	#endif

	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(0);

	int t=1;

	#ifdef TESTS
		cin>>t;
	#endif
	while(t--)
	{
		solve();
	}
	return 0;
}