Pagini recente » Cod sursa (job #2753132) | Cod sursa (job #2830402) | Cod sursa (job #656649) | Cod sursa (job #629357) | Cod sursa (job #2170219)
#include <fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int Find(int);
void Union(int, int);
int h[100005], tata[100005];
int main()
{
int n, m, tip, a, b;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> tip >> a >> b;
if (tip == 1)
{
int x = Find(a);
int y = Find(b);
Union(x, y);
}
else
{
int x = Find(a);
int y = Find(b);
if (x == y) fout << "DA\n";
else fout << "NU\n";
}
}
return 0;
}
void Union(int x, int y)
{
if (x != y)
{
if (h[x] > h[y]) tata[x] = y;
else if (h[y] > h[x]) tata[y] = x;
else { tata[y] = x; h[x]++; }
}
}
int Find(int x)
{
int rad = x, y;
while (tata[rad])
rad = tata[rad];
if (rad != x)
{
y = tata[x];
while (y != rad)
{
tata[x] = rad;
x = y;
y = tata[x];
}
}
return rad;
}