Cod sursa(job #387154)

Utilizator cvicentiuCiorbaru Vicentiu Marian cvicentiu Data 26 ianuarie 2010 21:55:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#define MaxN 100001

using namespace std;

fstream fin ("disjoint.in", ios::in);
fstream fout("disjoint.out",ios::out);

struct nod {
	int x;
	nod *urm;
};

int N, M, height[MaxN];
nod *loc[MaxN];

void merge(int x, int y){
	nod *p, *q;	
	
	for (p = loc[x]; p->urm != NULL; p = p->urm);
	for (q = loc[y]; q->urm != NULL; q = q->urm);
		
	if (height[x] > height[y])
		q->urm = p;
	else p->urm = q;

	height[x] += height[y];
	height[y] = height[x];
};

int search(int x, int y){
	nod *p, *q, *r, *s;

	for (p = loc[x]; p->urm != NULL; p = p->urm);
	for (q = loc[y]; q->urm != NULL; q = q->urm);

	/*for (r = loc[x]; r->urm != NULL;){
		s = r;
		r = r->urm;
		s->urm = p;
	};

	for (r = loc[y]; r->urm != NULL;){
		s = r;
		r = r->urm;
		s->urm = q;
	};*/

	if (p == q)
		return 1;
	
	return 0;
};

int main(){
	int cod, x, y;

	fin >> N >> M;
	for (int i = 1; i <= N; i++){
		loc[i] = new nod;
		loc[i]->x = i;
		loc[i]->urm = NULL;
	};

	for (int i = 1; i <= M; i++){
		fin >> cod >> x >> y;
		if (cod == 1)
			merge(x, y);
		else{
			if (search(x, y)) fout<<"DA\n";
			else fout<<"NU\n"; //check for error here
		};
	};

};