Pagini recente » Cod sursa (job #1217536) | Cod sursa (job #1409485) | Cod sursa (job #2469859) | Cod sursa (job #2065215) | Cod sursa (job #962997)
Cod sursa(job #962997)
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
// Maximum number of sets.
const size_t MAXN = 100010;
/* Array which holds the sets information as a forrest of trees.
* The root of the tree is the representative of the set.
*/
size_t sets_forest[MAXN];
// Array which is used to perform the path-compresion heuristic.
size_t height_set[MAXN];
void init(size_t n)
{
for (size_t i = 0; i <= n; ++i)
{
sets_forest[i] = i;
height_set[i] = 0;
}
}
// Finds the representative/name os the set to which s belongs to.
size_t find_set(size_t s)
{
if (sets_forest[s] != s)
sets_forest[s] = find_set(sets_forest[s]);
return sets_forest[s];
}
// Performs the union of the sets containing elements s1 and s2.
void union_sets(size_t s1, size_t s2)
{
s1 = find_set(s1);
s2 = find_set(s2);
if (s1 != s2)
{
if (height_set[s1] > height_set[s2])
sets_forest[s2] = s1;
else if (height_set[s1] < height_set[s2])
sets_forest[s1] = s2;
else
{
sets_forest[s2] = s1;
height_set[s1]++;
}
}
}
int main()
{
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int N, m;
fin >> N >> m;
init(N);
for (; m; --m)
{
int op, x, y;
fin >> op >> x >> y;
if (op == 1) union_sets (x, y);
else if (find_set(x) == find_set(y))
fout << "DA\n";
else
fout << "NU\n";
}
fout.close();
return EXIT_SUCCESS;
}