Cod sursa(job #996026)

Utilizator gabrieligabrieli gabrieli Data 10 septembrie 2013 18:56:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
using namespace std;

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

int n, p[100010];

bool sameset(int x, int y)
{
	int t;
	while (p[x] != p[y]) {
		if (p[x] < p[y]) {
			if (x == p[x])
				return false;
			t = p[x];
			p[x] = p[t];
			x = t;
		} else {
			if (y == p[y])
				return false;
			t = p[y];
			p[y] = p[t];
			y = t;
		}
	}
	return true;
}

void unite(int x, int y)
{
    int t;
	while (p[x] != p[y])
	{
		if (p[x] < p[y])
		{
			if (x == p[x])
			{
				p[x] = p[y];
				break;
			}
			t = p[x];
			p[x] = p[y];
			x = t;
		}
		else
		{
			if (y == p[y])
			{
				p[y] = p[x];
				return;
			}
			t = p[y];
			p[y] = p[x];
			y = t;
		}
	} 
}

int main()
{
	int m;
	fin >> n >> m;

	for (int i = 1; i <= n; ++i)
		p[i] = i;
	     
	for (; m; --m)
	{
		int op, x, y;
	    fin >> op >> x >> y;
		if (op == 1)
			unite(x, y);
		else if (sameset(x, y))
			fout << "DA\n";
		else
			fout << "NU\n";
	}

	fout.close();
	return 0;
}