Cod sursa(job #1708852)

Utilizator theo.stoicanTheodor Stoican theo.stoican Data 28 mai 2016 00:23:20
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

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

int n,m;
vector<int> ranks;
vector<int> p;

int find (int x)
{
	int i, j;
	int y;
	for (i = x; i!=p[i]; i = p[i]);
	//path compression
	for (;p[x] != x;)
	{
		y = p[x];
		p[x] = i;
		x = y;
	}
	return i;
}

void unify(int x, int y)
{
	if (ranks[x] > ranks[y])
	{
		p[y] = x;
	}
	else
		p[x] = y;
	if (ranks[x] == ranks[y])
		ranks[y] ++;
}

int main()
{
	fin>>n>>m;
	ranks.resize(n+1);
	p.resize(n+1); 
	for (int i = 1; i <= n; i++)
	{
		ranks[i] = 1;
		p[i] = i;
	}
	int x,y,c;
	for (int i = 0; i <m; i++)
	{
		fin>>c>>x>>y;
		if (c == 2)
		{
			if (find(x) == find(y))
				fout<<"DA"<<endl;
			else
				fout<<"NU"<<endl;	
		}
		else if (c == 1)
		{
			if (find(x) == find(y))
			{
				cout<<i<<endl;
				return 0;
			}
				unify(x, y);
		}
	}
	return 0;
}