Pagini recente » Cod sursa (job #984314) | Cod sursa (job #8047) | Rating Danciu Eduard Florin (edidanciu) | Clasament simulare_nr1 | Cod sursa (job #2746618)
#include <fstream>
#include <vector>
using namespace std;
struct DisjointSetNode {
int parent;
int rank;
};
int representative_of(int x, DisjointSetNode* disjoint_set) {
vector<int> nodes;
while(disjoint_set[x].parent != x) {
nodes.push_back(x);
x = disjoint_set[x].parent;
}
for(const auto &t : nodes)
disjoint_set[t].parent = x;
return x;
}
int main() {
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
DisjointSetNode disjoint_set[100001];
int N, M;
fin >> N >> M;
for (int i = 1; i <= N; i++) {
disjoint_set[i].parent = i;
disjoint_set[i].rank = 1;
}
while(M--) {
int cod, x, y;
fin >> cod >> x >> y;
if(cod == 1) {
int rep_x = representative_of(x, disjoint_set);
int rep_y = representative_of(y, disjoint_set);
if(disjoint_set[rep_x].rank > disjoint_set[rep_y].rank) {
disjoint_set[rep_y].parent = rep_x;
}
else if(disjoint_set[rep_x].rank < disjoint_set[rep_y].rank) {
disjoint_set[rep_x].parent = rep_y;
}
else {
disjoint_set[rep_x].parent = rep_y;
disjoint_set[rep_y].rank++;
}
}
else
fout << (representative_of(x, disjoint_set) == representative_of(y, disjoint_set) ? "DA" : "NU") << '\n';
}
fin.close();
fout.close();
return 0;
}