Pagini recente » Borderou de evaluare (job #2914864) | Borderou de evaluare (job #2203182) | Borderou de evaluare (job #1473231) | Borderou de evaluare (job #1828749) | Cod sursa (job #3268062)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
vector<int> father;
vector<int> depth;
int FindRoot(int nod) {
if(father[nod] == nod)
return nod;
return father[nod] = FindRoot(father[nod]);
}
void Union(int x, int y) {
int r1 = FindRoot(x);
int r2 = FindRoot(y);
if(depth[r1] < depth[r2])
father[r1] = r2;
else if(depth[r1] > depth[r2])
father[r2] = r1;
else {
father[r1] = r2;
depth[r2]++;
}
}
int main() {
int N, M;
in >> N >> M;
father.resize(N+1);
depth.resize(N+1);
for(int i = 1; i <= N; i++) {
father[i] = i;
depth[i] = 0;
}
while(M--) {
int op, x, y;
in >> op >> x >> y;
if(op == 1) {
Union(x, y);
} else {
if(FindRoot(x) == FindRoot(y))
out << "DA\n";
else
out << "NU\n";
}
}
return 0;
}