Cod sursa(job #615077)

Utilizator vladbagrinVlad Bagrin vladbagrin Data 8 octombrie 2011 15:39:07
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 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;
		}
	}

	inline 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 {
			int root_x = forest.find(x), root_y = forest.find(y);
			if (root_x == root_y) {
				out << "DA" << endl;
			} else {
				out << "NU" << endl;
			}
		}
	}
	in.close();
	out.close();
	return SUCCESS;
}