Pagini recente » Cod sursa (job #2020654) | Cod sursa (job #2148844) | Cod sursa (job #2425209) | Cod sursa (job #1565442) | Cod sursa (job #1790546)
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
ifstream fi("disjoint.in");
ofstream fo("disjoint.out");
struct node {
int data, rank;
node* father;
};
node* FIND(node* x);
void UNION(int x, int y);
void init();
node* sets[100001];
int N, Q;
int main()
{
init();
for (int i = 1;i <= Q;i++)
{
int c, x, y;
fi >> c >> x >> y;
if (c == 2)
{
if (FIND(sets[x]) == FIND(sets[y]))
fo << "DA\n";
else fo << "NU\n";
}
else
UNION(x, y);
}
}
void init()
{
fi >> N >> Q;
for (int i = 1;i <= N;i++)
{
node* n = new node;
n->data = i;
n->father = NULL;
n->rank = 1;
sets[i] = n;
}
}
void UNION(int x, int y)
{
if (sets[y]->rank < sets[x]->rank)
{
node* n = sets[y];
while (n->father != NULL)
n = n->father;
sets[n->data]->father = sets[x];
sets[y]->rank += sets[x]->rank;
}
else
{
node* n = sets[x];
while (n->father != NULL)
n = n->father;
sets[n->data]->father = sets[y];
sets[x]->rank += sets[y]->rank;
}
return;
}
node* FIND(node* x)
{
if (x->father != NULL)
x->father = FIND(x->father);
return x;
}