Cod sursa(job #2940938)

Utilizator SurtexXGheorghe Robert-Mihai SurtexX Data 16 noiembrie 2022 19:42:15
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");
vector<int> root;

int getroot(int x)
{
	while (root[x] != x)
	{
		root[x] = root[root[x]];
		x = root[x];
	}
	return x;
}
void union1(int x, int y)
{
	int p = getroot(x);
	int q = getroot(y);
	root[q] = root[p];
}

int main()
{
	int n, m, cod, x, y;
	f >> n >> m;
	vector<vector<int>> adjacence_list(n+1, vector<int>(0));
	root = vector<int>(n + 1);
	for (int i = 1; i <= n; i++)
	{
		adjacence_list[i].push_back(i);
		root[i] = i;
	}
	for (int i = 1; i <= m; i++)
	{
		f >> cod >> x >> y;
		if (cod == 1) {
			for (int j = 0; j < adjacence_list[y].size(); j++)
			{
				adjacence_list[x].push_back(adjacence_list[y][j]);
				union1(x, adjacence_list[y][j]);
			}
		}
		else
		{
			if (root[x] == root[y])
				g << "DA\n";
			else
				g << "NU\n";
		}
	}
	return 0;
}