Cod sursa(job #3218544)

Utilizator george_buzasGeorge Buzas george_buzas Data 27 martie 2024 12:42:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#define NR_MAX_NODES 100000
using namespace std;

// value of the query is 1 - unify the 2 components if necessary
// value of the query is 2 - specify whether the 2 nodes belong to the same component or not

int parents[NR_MAX_NODES + 1];

int findParents(int node) {
	if (!parents[node]) {
		return node;
	}
	return findParents(parents[node]);
}

void unifyComponents(int parent1, int parent2) {
	parents[parent2] = parent1;
}

int main() {
	ifstream fin("disjoint.in");
	ofstream fout("disjoint.out");
	fin.tie(0);
	int nrNodes, nrQueries;
	fin >> nrNodes >> nrQueries;
	while (nrQueries--) {
		int operationType, node1, node2;
		fin >> operationType >> node1 >> node2;
		int parent1 = findParents(node1);
		int parent2 = findParents(node2);
		if (operationType == 1) {
			if (parent1 != parent2) {
				unifyComponents(parent1, parent2);
			}
		} else {
			if (parent1 == parent2) {
				fout << "DA\n";
			} else {
				fout << "NU\n";
			}
		}
	}
	return 0;
}