Pagini recente » Cod sursa (job #2942940) | Cod sursa (job #226030) | Cod sursa (job #742889) | Cod sursa (job #2850724) | Cod sursa (job #2546948)
#include<fstream>
#include<iostream>
#define MAX_N 100000
using namespace std;
int p[MAX_N + 1], h[MAX_N + 1], n, m;
void Init(int n) {
for(int i = 1; i <= n; i++) {
p[i] = i;
h[i] = 1;
}
}
int Find(int x) {
int r, aux;
r = x;
while(r != p[r])
r = p[r];
while(p[x] != r) {
aux = p[x];
p[x] = r;
x = aux;
}
return r;
}
void Union(int x, int y) {
int rootx, rooty;
rootx = Find(x);
rooty = Find(y);
if(h[rootx] < h[rooty])
p[rootx] = rooty;
else if(h[rootx] > h[rooty])
p[rooty] = rootx;
else {
p[rootx] = rooty;
h[rooty]++;
}
}
int main() {
int n, m, op, x, y;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
fin >> n >> m;
Init(n);
for(int i = 1; i <= m; i++) {
fin >> op >> x >> y;
//cout << op << " " << x << " " << y << "\n";
if(op == 1)
Union(x, y);
else {
if(Find(x) == Find(y))
fout << "DA\n";
else fout << "NU\n";
}
}
fin.close();
fout.close();
return 0;
}