Cod sursa(job #1944223)

Utilizator vlcmodanModan Valentin vlcmodan Data 29 martie 2017 00:12:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include<stdio.h>
#include<iostream>
#include<vector>

#define v_i vector<int>
#define v_ip vector<int>*
using namespace std;


int n, m;
int type, x, y;

void unify(vector<int>& t,vector<int> &r, int x, int y)
{
	if (r[x] > r[y])
	{
		t[x] = y;
	}
	else
	{
		t[y] = x;
	}

	if (r[x] ==r[y])
	{
		r[x]++;
	}


}

int found(vector<int> &t, int x)
{

	int rad = x;
	int aux;

	for (rad = x; rad != t[rad]; rad = t[rad]);

	while (x != rad)
	{
		aux = t[x];
		t[x] = rad;
		x = aux;
	}

	return rad;

}
void initialize(vector<int>& t,vector<int>& r)
{
	for (int i = 1; i < t.size(); i++)
	{
		t[i] = i;
		r[i] = 1;
	}
}


int main()
{
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);

	scanf("%d %d", &n, &m);

	v_i t(n + 1);
	v_i r(n + 1);

	initialize(t, r);

	for (int i = 1; i <= m; i++)
	{
		scanf("%d %d %d", &type, &x, &y);

		if (type == 1)
		{
			unify(t, r, found(t, x), found(t, y));
		}
		else
		{
			if (found(t, x) == found(t, y))
			{
				printf("DA\n");
			}
			else
			{
				printf("NU\n");
			}
		}
	}




	return 0;
}