Pagini recente » Cod sursa (job #236288) | Cod sursa (job #808069) | Cod sursa (job #2527058) | Cod sursa (job #2836613) | Cod sursa (job #2054726)
#include<iostream>
#include<fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
const int N = 100001;
int boss[N],n,m;
void update(int a, int b) /// Joins A and B's families
{
while(a != boss[a]) a = boss[a];
while(b != boss[b]) b = boss[b];
boss[a] = boss[b];
}
int getBoss(int x)
{
int stack[N], stackLength = 0;
while(x != boss[x]) /// Haven't found the boss yet
{
stack[stackLength++] = x;
x = boss[x];
}
for(int index=0; index < stackLength; ++index)
boss[stack[index]] = boss[x]; /// Every visited node has its 'boss' updated to the X's boss = the biggest boss
return x; /// Return the boss
}
void query(int a, int b)
{
if(getBoss(a) == getBoss(b)) out<<"DA\n";
else out<<"NU\n";
}
void afis()
{
int i;
for(i=1; i<=n; ++i) cout<<i<<" "; cout<<"\n";
for(i=1; i<=n; ++i) cout<<boss[i]<<" "; cout<<"\n";
cout<<"\n";
}
int main()
{
in>>n>>m;
for(int i=1; i<=n; ++i) boss[i] = i;
for(int i=0; i<m; ++i)
{
int tip,x,y;
in>>tip>>x>>y;
if(tip == 1) update(x, y);
else if(tip == 2) query(x, y);
}
return 0;
}