Cod sursa(job #3145104)

Utilizator David8406Marian David David8406 Data 12 august 2023 17:47:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
	#include <iostream>
	#include <algorithm>
	#include <fstream>
	using namespace std;
	ifstream fin("disjoint.in");
	ofstream fout("disjoint.out");
	int n, m, tip, x, y, p[100005], sz[100005];
	int get_parent(int nod) {
		int cpy = nod;
		while (p[cpy] != 0) {
			cpy = p[cpy];
		}
		while (p[nod] != 0) {
			int cpy2 = p[nod];
			p[nod] = cpy;
			nod = cpy2;
		} ///optimizare path compresion
		return cpy;
	}
	void unite(int x, int y) {
		x = get_parent(x);
		y = get_parent(y);
		if (x == y) return;
		if (sz[x] < sz[y]) {
			p[x] = y;
			sz[y] += sz[x];
		}
		else {
			p[y] = x;
			sz[x] += sz[y];
		}
	}
	int main() {
		fin >> n >> m;
		for (int i = 1; i <= m; i++) {
			p[i] = 0;
			sz[i] = 1;
		}
		for (int i = 1; i <= m; i++) {
			fin >> tip >> x >> y;
			if (tip == 1) unite(x, y);
			else {
				if (get_parent(x) == get_parent(y)) fout << "DA" << "\n";
				else fout << "NU" << "\n";
			}
		}
	}