Cod sursa(job #956400)

Utilizator gabrieligabrieli gabrieli Data 3 iunie 2013 00:28:48
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;

const int MAXN = 100010;
int uf[MAXN], rank[MAXN];

int find (int x)
{
	int representative = x;
	
	for (; representative != uf[representative]; representative = uf[representative]);
	
	int t;
	while (x != uf[x]) 
	{
    	t = x;
    	x = uf[t];
    	uf[t] = representative;
	}
	
	return representative;
}

void union_find (int x, int y)
{
	x = find (x);
	y = find (y);
	if (rank[x] > rank[y])
		uf[y] = x;
	else
	{
		uf[x] = y;
		if (rank[x] == rank[y])
			rank[y]++;
	}
}

int main()
{
	ifstream fin ("disjoint.in");
	ofstream fout ("disjoint.out");

	int N, m;
	fin >> N >> m;
	for (int i = 1; i <= N; ++i)
		uf[i] = i;

	for (; m; --m)
	{
		int op, x, y;
		fin >> op >> x >> y;
		if (op == 1) union_find (x, y);
		else if (find(x) == find(y))
			fout << "DA\n";
		else
			fout << "NU\n";
	}

	fout.close();
	return EXIT_SUCCESS;
}