Cod sursa(job #3148776)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 4 septembrie 2023 10:32:59
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

const int mxN = 1e5 + 5;

int tata[mxN], grad[mxN];

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

int root(int node) {
	while (node != tata[node])
		node = tata[node];
	return node;
}

void add_union(int node_a, int node_b) {
	if (grad[node_a] > grad[node_b]) {
		tata[node_b] = node_a;
		grad[node_a] += grad[node_b];
	} else {
		tata[node_a] = node_b;
		grad[node_b] += grad[node_a];
	}
}

int main() {
	int n, m;
	fin >> n >> m;
	for (int i = 1; i <= n; ++i) {
		tata[i] = i;
		grad[i] = 1;
	}

	while (m--) {
		int op, x, y;
		fin >> op >> x >> y;
		if (op == 1) {
			if (root(x) != root(y)) {
				add_union(root(x), root(y));	
			}
		} else {
			if (root(x) == root(y)) {
				fout << "DA\n";
			} else {
				fout << "NU\n";
			}
		}
	}
	return 0;
}