Cod sursa(job #1834258)

Utilizator Rocamadour1497Alexandru Martiniuc Rocamadour1497 Data 24 decembrie 2016 10:27:45
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
#define nmax 100005
int tt[nmax], rang[nmax];
int find(int x)
{
	int root, y;
	for (root = x; tt[root] != root; root = tt[root]);
	for (; tt[x] != x;)
	{
		y = tt[x];
		tt[x] = root;
		x = y;
	}
	return root;
}

void unite(int a, int b)
{
    if(rang[a]>rang[b])
    tt[b]=a;
    else tt[a]=b;
    if(rang[a]==rang[b]) rang[b]++;
}
int main()
{
	int n, m, i;
	f >> n;
	f >> m;
	for (i = 1; i <= n; i++)
	{
		tt[i] = i;
		rang[i] = 1;
	}
	while (m--)
	{
		int b, x, y;
		f >> b >> x >> y;
		if (b == 1)
		{
			unite(find(x), find(y));
		}
		else {
			if (find(x) == find(y)) g << "DA"<<'\n';
			else g << "NU" <<'\n';
		}
	}
}