Pagini recente » Statisticile problemei Triaj | Monitorul de evaluare | Statisticile problemei Emptri | Profil emysp2005 | Cod sursa (job #2001179)
/*
Disjoint Set Union
Time Complexity: O(nlogn) - build, O(log* n) - query
Memory: O(n)
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cassert>
using namespace std;
class DisjointSetUnion {
private:
int n;
vector<int> parent;
vector<int> weight;
public:
DisjointSetUnion(const int n) {
this->n = n;
parent.resize(n);
weight.resize(n);
for (int i = 0; i < n; ++i) {
parent[i] = i;
weight[i] = 1;
}
}
int getRoot(int node) {
int root;
for (root = node; root != parent[root]; root = parent[root]);
int aux;
while (node != parent[node]) {
aux = parent[node];
parent[node] = root;
node = aux;
}
return root;
}
void unite (int x, int y) {
x = getRoot(x);
y = getRoot(y);
if (x == y)
return;
if (weight[x] > weight[y])
parent[y] = x;
else
parent[x] = y;
if (weight[x] == weight[y])
weight[y]++;
}
};
int main() {
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int N, M;
fin >> N >> M;
DisjointSetUnion dsu(N);
int x, a, b;
while (M--) {
fin >> x >> a >> b;
a--;
b--;
if (x == 1)
dsu.unite(a, b);
else
fout << (dsu.getRoot(a) == dsu.getRoot(b) ? "DA" : "NU") << "\n";
}
return 0;
}