Pagini recente » Cod sursa (job #1855465) | Cod sursa (job #2275338) | Cod sursa (job #1009862) | Cod sursa (job #2982853) | Cod sursa (job #2945597)
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
vector<int> tata(100001), rang(100001);
int N, M;
int findAncestor(int k){
///we recursively traverse the fathers vector to find the one node that doesn't have a father
if(tata[k]) {
tata[k] = findAncestor(tata[k]);
return tata[k];
}
return k;
}
void Union(int x, int y){
if(x != y) {
///if the x node has a bigger rank than y, than the father of y is x
/// so that we unite the 2 sets under one node
if (rang[x] > rang[y])
tata[y] = x;
else
tata[x] = y;
///if 2 nodes have the same rank, we arbitrary choose x and increment its rank
if(rang[x] == rang[y])
rang[x]++;
}
}
int main(){
f >> N >> M;
int op, x, y;
while (M--){
f >> op >> x >> y;
if(op == 1){
Union(findAncestor(x), findAncestor(y));
}
else{
if(findAncestor(x) == findAncestor(y))
g << "DA\n";
else
g << "NU\n";
}
}
f.close();
g.close();
return 0;
}