Cod sursa(job #2421204)

Utilizator dadada876Cinca Adrian dadada876 Data 14 mai 2019 14:46:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
//#include "pch.h"
#include <iostream>
#include<fstream>
#include<vector>
using namespace std;

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

struct arbore {
	int n;
	vector<int> tata, rang;
	arbore(int a) :n(a), tata(a + 1), rang(a + 1, 1)
	{
		for (int i = 1; i <= a; i++)
			tata[i] = i;
	}
	int find_father(int x) {
		if (x == tata[x])
			return x;
		else {
			int dad = find_father(tata[x]);
			tata[x] = dad;
			return dad;
		}
	}
	void op1(int x, int y) {
		int tx, ty;
		tx = find_father(x);
		ty = find_father(y);
		if (rang[tx] < rang[ty]) {
			tata[tx] = ty;
			rang[ty] += rang[tx];
		}
		else {
			tata[ty] = tx;
			rang[tx] += rang[ty];
		}
	}
	void op2(int x, int y) {
		if (find_father(x) == find_father(y))
			out << "DA\n";
		else
			out << "NU\n";
	}
};
int main()
{
	int N, M,x,y,op;
	in >> N >> M;
	arbore A(N);
	for (int i = 0; i < M; i++) {
		in >> op >> x >> y;
		if (op == 1)
			A.op1(x, y);
		else
			A.op2(x, y);
	}

	in.close();
	out.close();
	return 0;
}