Pagini recente » Cod sursa (job #71536) | Cod sursa (job #219686) | Cod sursa (job #678005) | Cod sursa (job #1256735) | Cod sursa (job #1793573)
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <map>
using namespace std;
ifstream fi("disjoint.in");
ofstream fo("disjoint.out");
const int maxn = 100000;
struct node{
int data, rang;
node* father;
};
node* v[maxn];
int M,N;
void init();
void UNION(node* a, node* b);
node* FIND(node* a);
void solve();
int main()
{
init();
solve();
return 0;
}
void init()
{
fi>>N>>M;
for(int i=1;i<=N;i++)
{
node* a = new node;
a->data = i;
a->father = NULL;
a->rang=0;
v[i] = a;
}
return;
}
void solve()
{
for(int i=1;i<=M;i++)
{
int q,x,y;
fi>>q>>x>>y;
if(q==1)
UNION(v[x],v[y]);
else
{
if(FIND(v[x]) == FIND(v[y]))
fo<<"DA\n";
else fo<<"NU\n";
}
}
return;
}
void UNION(node* a, node* b)
{
if(a->rang > b->rang)
{
while(b->father != NULL)
b=b->father;
v[b->data]->father = a;
}
else if(b->rang > a->rang)
{
while(a->father != NULL)
a=a->father;
v[a->data]->father = b;
}
else
{
while(b->father != NULL)
b=b->father;
v[b->data]->father = a;
v[a->data]->rang++;
}
}
node* FIND(node* a)
{
node* n = v[a->data];
if(n->father!=NULL)
n->father = FIND(n->father);
else if(n->father ==NULL)
return n;
return n->father;
}