Pagini recente » Cod sursa (job #1841971) | Borderou de evaluare (job #3288481) | muchiipermutate | Cod sursa (job #3314014) | Cod sursa (job #449273)
Cod sursa(job #449273)
/*
* File: main.cpp
* Author: Johnny
*
* Created on May 6, 2010, 3:58 AM
*/
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct element {
int parent;
int rank;
};
element * x;
int find(int a);
void unite(int a, int b);
int main(int argc, char** argv) {
int n, m;
FILE * f = fopen("disjoint.in", "r");
fscanf(f, "%d %d", &n, &m);
x = new element[n];
for (int i = 0; i < n; ++i) {
x[i].parent = i;
x[i].rank = 0;
}
FILE * g = fopen("disjoint.out", "w");
int a, b, option;
for (int i = 0; i < m; ++i) {
fscanf(f, "%d %d %d", &option, &a, &b);
if (option == 1) {
unite(a - 1, b - 1);
} else {
if (find(a - 1) == find(b - 1))
fprintf(g, "DA\n");
else
fprintf(g, "NU\n");
}
}
fclose(f);
fclose(g);
delete [] x;
return (EXIT_SUCCESS);
}
int find(int a) {
int root = a;
while (root != x[root].parent)
root = x[root].parent;
int next;
while (x[a].parent != root) {
next = x[a].parent;
x[a].parent = root;
a = next;
}
return root;
}
void unite(int a, int b) {
int aRoot = find(a);
int bRoot = find(b);
if (aRoot > bRoot)
x[bRoot].parent = aRoot;
else if (aRoot < bRoot)
x[aRoot].parent = bRoot;
else {
x[bRoot].parent = aRoot;
++x[aRoot].rank;
}
}