Cod sursa(job #615083)

Utilizator vladbagrinVlad Bagrin vladbagrin Data 8 octombrie 2011 15:54:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>

#define INPUT "disjoint.in"
#define OUTPUT "disjoint.out"
#define MAX 100001
#define SUCCESS 0

using namespace std;

class Forest {
private:
	int parent[MAX], rank[MAX];

public:
	Forest(int n) {
		for (int i = 0; i <= n; i++) {
			parent[i] = i;
			rank[i] = 0;
		}
	}

	int find(int x) {
		if (parent[x] == x) {
			return x;
		} else {
			parent[x] = find(parent[x]);
			return parent[x];
		}
	}

	inline void unify(int x, int y) {
		int root_x = find(x), root_y = find(y);
		if (root_x != root_y) {
			if (rank[root_x] <= rank[root_y]) {
				parent[root_x] = root_y;
				if (rank[root_x] == rank[root_y]) {
					rank[root_y]++;
				}
			} else {
				parent[root_y] = root_x;
			}
		}
	}
};

int main() {
	ifstream in(INPUT, ifstream::in);
	ofstream out(OUTPUT, ofstream::out);
	int n, m;
	in >> n;
	Forest forest(n);
	in >> m;
	for (int i = 0; i < m; i++) {
		int op, x, y;
		in >> op;
		in >> x;
		in >> y;
		if (op == 1) {
			forest.unify(x, y);
		} else {
			if (forest.find(x) == forest.find(y)) {
				out << "DA\n";
			} else {
				out << "NU\n";
			}
		}
	}
	in.close();
	out.flush();
	out.close();
	return SUCCESS;
}