Mai intai trebuie sa te autentifici.
Cod sursa(job #1896235)
| Utilizator | Data | 28 februarie 2017 16:07:36 | |
|---|---|---|---|
| Problema | Paduri de multimi disjuncte | Scor | 100 |
| Compilator | cpp | Status | done |
| Runda | Arhiva educationala | Marime | 1.23 kb |
#include <cstdio>
#include <stack>
using namespace std;
struct node{
int rank;
int parent;
}node[100001];
int Find(int target){
int root, y;
for(root = target; node[root].parent != root; root = node[root].parent);
for(; node[target].parent != target;){
y = node[target].parent;
node[target].parent = root;
target = y;
}
return root;
}
void Union(int x, int y){
int rootX = Find(x);
int rootY = Find(y);
if(node[rootX].rank > node[rootY].rank){
node[rootY].parent = rootX;
}else{
if(node[rootX].rank == node[rootY].rank){
node[rootY].rank++;
}
node[rootX].parent = rootY;
}
}
int main(){
int sets, queries, task, x, y;
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
scanf("%d %d", &sets, &queries);
for(int i = 1; i <= sets; i++){
node[i].rank = 1;
node[i].parent = i;
}
for(int i = 1; i <= queries; i++){
scanf("%d %d %d", &task, &x, &y);
if(task == 1){
Union(x, y);
}else{
printf("%s\n", (Find(x) == Find(y)) ? "DA" : "NU");
}
}
return 0;
}
