Cod sursa(job #1721192)

Utilizator theo.stoicanTheodor Stoican theo.stoican Data 24 iunie 2016 19:45:34
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

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

int n,m;
int RG[100020];
int TT[100020];

int find(int x)
{
    int R, y;
 
    //merg in sus pe arbore pana gasesc un nod care pointeaza catre el insusi
    for (R = x; TT[R] != R; R = TT[R]);
 
    //aplic compresia drumurilor
    for (; TT[x] != x;)
    {
        y = TT[x];
        TT[x] = R;
        x = y;
    }
    return R;
}

void unify(int x, int y)
{
    //unesc multimea cu rang mai mic de cea cu rang mai mare
    if (RG[x] > RG[y])
        TT[y] = x;
            else TT[x] = y;
 
    //in caz ca rangurile erau egale atunci cresc rangul noii multimi cu 1
    if (RG[x] == RG[y]) RG[y]++;
}

int main()
{
	fin>>n>>m;
	for (int i = 1; i <= n; i++)
	{
		RG[i] = 1;
		TT[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)
		{
			int px = find(x);
			int py = find(y);
			if (px == py)
			{
				cout<<i<<endl;
				return 0;
			}
			unify(px, py);
		}
	}
	return 0;
}