Pagini recente » Cod sursa (job #576524) | Cod sursa (job #314991) | Cod sursa (job #1703881) | Cod sursa (job #946613) | Cod sursa (job #3252786)
#include <iostream>
#include <vector>
using namespace std;
const int NMAX = 1e5;
struct DSU {
vector<int> h, p;
DSU(int n) {
h.resize(n + 1);
p.resize(n + 1);
for(int i = 1; i <= n; i++) {
h[i] = 1;
p[i] = i;
}
}
int Find(int x) {
int r = x;
while(r != p[r]) {
r = p[r];
}
int y = x;
while(y != r) {
int t = p[y];
p[y] = r;
y = t;
}
return r;
}
void Union(int x, int y) {
x = Find(x);
y = Find(y);
if(x != y) {
if(h[x] < h[y]) {
p[x] = y;
} else {
if(h[y] < h[x]) {
p[y] = x;
} else {
p[y] = x;//p[x] = y si h[y]++;
h[x]++;
}
}
}
}
};
int main()
{
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n, m;
f >> n >> m;
DSU d(n);
for(int i = 1; i <= m; i++) {
int op, x, y;
f >> op >> x >> y;
if(op == 1) {
d.Union(x, y);
} else {
if(d.Find(x) == d.Find(y)) {
g << "DA\n";
} else {
g << "NU\n";
}
}
}
return 0;
}