Pagini recente » Cod sursa (job #1535476) | Cod sursa (job #3162451) | Cod sursa (job #2373525) | Cod sursa (job #2683098) | Cod sursa (job #2291485)
#include <iostream>
#include <fstream>
#define NMAX 100010
using namespace std;
int fathers[NMAX], height[NMAX];
int findFather(int f)
{
int fatherVal;
for (fatherVal=f; fatherVal!=fathers[fatherVal]; fatherVal=fathers[fatherVal]){}
for (; f!=fathers[f]; f=fathers[f])
fathers[f] = fathers[fatherVal], height[f] = height[fatherVal];
return fatherVal;
}
void unite(int x, int y)
{
if(height[x] > height[y])
fathers[y] = fathers[x];
else
fathers[x] = fathers[y];
if (height[x] == height[y])
height[x] = height[y] = height[x] + 1;
}
int main()
{
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n, m, x, y, k;
fin >> n >> m;
for (int i=1; i<=n; i++)
{
fathers[i] = i;
height[i] = 1;
}
for (int i=1; i<=m; i++)
{
fin >> k >> x >> y;
if (k == 1)
{
if (findFather(x) == findFather(y))
return 0;
unite(x, y);
}
else
{
if (findFather(x) == findFather(y))
fout << "DA\n";
else
fout << "NU\n";
}
}
return 0;
}