Cod sursa(job #2424826)

Utilizator mateigabriel99Matei Gabriel mateigabriel99 Data 23 mai 2019 21:45:15
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
using namespace std;

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

int N, M;
map<int, int> state;
map<int, int> father;

int GetRoot(int root)
{
	while (root != father[root])
		root = father[root];
	return root;
}

void Unite(int x, int y)
{
	if (state[x] > state[y])
		father[y] = x;
	else
		father[x] = y;

	if (state[x] == state[y])
		father[y]++;
}

int main()
{
	fin >> N >> M;

	for (int i = 1; i <= N; i++)
		state[i] = father[i] = i;

	for (int i = 0; i < M; i++)
	{
		int c, x, y;
		fin >> c >> x >> y;

		int rootX = GetRoot(x);
		int rootY = GetRoot(y);

		if (c == 1)
			Unite(rootX, rootY);
		else
			rootX == rootY ? fout << "DA\n" : fout << "NU\n";
	}

	return 0;
}