Cod sursa(job #1105025)

Utilizator cdt2014Cont de Teste cdt2014 Data 11 februarie 2014 13:02:04
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <vector>
#include <fstream>
using namespace std;

class DisjointSets {
	public:
		DisjointSets(int N) : father(N), depth(N) {
			for (int i=0; i<N; ++i) { 
				father[i] = i;
				depth[i] = 1;
			}
		}

		void join(int x, int y) {
			int fx = getSet(x);
			int fy = getSet(y);
			if (x == y) {
				return ;
			}

			if (depth[x] == depth[y]) {
				depth[x] ++;
				father[x] = y;
			} else {
				if (depth[x] < depth[y]) {
					father[x] = y;
				} else {
					father[y] = x;
				}
			}
		}

		bool sameSet(int x, int y) { 
			return getSet(x) == getSet(y);
		}

	private:
		vector<int> depth, father;

		int getSet(int x) {
			while (father[x] != x) x = father[x];
			return x;
		}
};

int main() { 
	ifstream in("disjoint.in");
	ofstream out("disjoint.out");
	int N, Q;

	in >> N >> Q;
	DisjointSets ds(N);
	while (Q--) {
		int q, x, y;
		in >> q >> x >> y;
		switch (q) {
			case 1:
				ds.join(x, y);
				break;
			case 2:
				out << (ds.sameSet(x, y) ? "DA\n" : "NU\n");
				break;
		}
	}
	return 0;
}