Pagini recente » Cod sursa (job #659216) | Cod sursa (job #484280) | Cod sursa (job #1573551) | Borderou de evaluare (job #804543) | Cod sursa (job #1105031)
#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 (fx == fy) {
return ;
}
if (depth[fx] == depth[fy]) {
depth[fy] ++;
father[fx] = fy;
} else {
if (depth[fx] < depth[fy]) {
father[fx] = y;
} else {
father[fy] = fx;
}
}
}
bool sameSet(int x, int y) {
return getSet(x) == getSet(y);
}
private:
vector<int> father;
vector<int> depth;
int getSet(int x) {
if (x == father[x]) return x;
father[x] = getSet(father[x]);
depth[x] = 2;
return father[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;
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;
}