Pagini recente » Cod sursa (job #821071) | Cod sursa (job #286478) | Cod sursa (job #447572) | Cod sursa (job #1787722) | Cod sursa (job #449270)
Cod sursa(job #449270)
/*
* File: main.cpp
* Author: Johnny
*
* Created on May 6, 2010, 3:58 AM
*/
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
struct element {
int parent;
int rank;
};
element * x;
int find(int a);
int unite(int a, int b);
int main(int argc, char** argv) {
int n, m;
fstream f("disjoint.in", ios_base::in);
f >> n >> m;
x = new element[n];
for (int i = 0; i < n; ++i) {
x[i].parent = i;
x[i].rank = 0;
}
fstream g("disjoint.out", ios_base::out);
int a, b, option;
for (int i = 0; i < m; ++i) {
f >> option >> a >> b;
if (option == 1) {
unite(a - 1, b - 1);
} else {
if (find(a - 1) == find(b - 1))
g << "DA" << endl;
else
g << "NU" << endl;
}
}
f.close();
g.close();
delete [] x;
return (EXIT_SUCCESS);
}
int find(int a) {
if (x[a].parent == a)
return a;
x[a].parent = find(x[a].parent);
return x[a].parent;
}
int 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;
}
}