Cod sursa(job #2251788)

Utilizator aurelionutAurel Popa aurelionut Data 1 octombrie 2018 22:41:41
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>

using namespace std;

const int NMAX = 1e5 + 10;
int father[NMAX], cnt[NMAX];
int n, m;

inline void Union(int x, int y)
{
	cnt[x] += cnt[y];
	father[y] = x;
}

int Find(int x)
{
	int r = x;
	while (father[r] != 0)
		r = father[r];
	int aux;
	while (x != r)
	{
		aux = father[x];
		father[x] = r;
		x = aux;
	}
	return r;
}

int main()
{
	ifstream fin("disjoint.in");
	ofstream fout("disjoint.out");
	fin >> n >> m;
	for (int i = 1;i <= n;++i)
		cnt[i] = 1;
	int op, x, y;
	for (int i = 1;i <= m;++i)
	{
		fin >> op >> x >> y;
		x = Find(x);
		y = Find(y);
		if (op == 1 && x != y)
			Union(x, y);
		if (op == 2)
			fout << (x == y ? "DA\n" : "NU\n");
	}
	fin.close();
	fout.close();
	return 0;
}