Cod sursa(job #2227187)

Utilizator mihai50000Mihai-Cristian Popescu mihai50000 Data 31 iulie 2018 14:06:28
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.73 kb
#include <bits/stdc++.h>

using namespace std;

#define IOS ios::sync_with_stdio(false), cin.tie(0);

ifstream in("disjoint.in");
ofstream out("disjoint.out");

const int N = 1e5 + 7;

int TO[N];
int R[N];

int find(int nod)
{
	int i;
	for(i = nod; TO[i] != i; i = TO[i]);
	for(; TO[nod] != nod;)
	{
		int y = TO[nod];
		TO[nod] = i;
		nod = y;
	}
	return i;
}

void unite(int x, int y)
{
	if(R[x] > R[y])
		TO[y] = x;
	else
		TO[x] = y;
	if(R[x] == R[y])
		R[y]++;
}

main()
{
	IOS
	int n, m;
	in >> n >> m;
	for(int i = 1; i <= n; i++)
	{
		TO[i] = i;
		R[i] = 1;
	}
	for(int i = 1; i <= m; i++)
	{
		int op, x, y;
		in >> op >> x >> y;
		if(op == 1)
			unite(find(x), find(y));
		else
			out << ((find(x) == find(y)) ? "DA\n" : "NU\n");
	}
}