Pagini recente » Cod sursa (job #2582180) | Cod sursa (job #2598295) | Cod sursa (job #1846257) | Cod sursa (job #2977028)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int t[100001];
int h[100001];
int n, k;
void initializare()
{
for(int i = 1; i <= n; ++i)
{
t[i] = i;
h[i] = 1;
}
}
int gasim_tata(int x)
{
int aux = x;
while(t[x] != x)
x = t[x];
while(aux != x)
{
int next = t[aux];
t[aux] = x;
aux = next;
}
return x;
}
void unire(int x, int y)
{
int tata_y = gasim_tata(y);
int tata_x = gasim_tata(x);
if(h[tata_y] < h[tata_x])
{
t[tata_y] = tata_x;
h[tata_y] = h[tata_x];
}
else if(h[tata_x] < h[tata_y])
{
t[tata_x] = tata_y;
h[tata_x] = h[tata_y];
}
else
{
t[tata_x] = tata_y;
h[tata_y]++;
h[tata_x] = h[tata_y];
}
}
void rezolvare()
{
int op, x, y;
for(int j = 0; j < k; ++j)
{
fin >> op >> x >> y;
if(op == 1)
unire(x, y);
else
{
if(gasim_tata(x) == gasim_tata(y))
fout << "DA\n";
else
fout << "NU\n";
}
}
}
int main()
{
fin >> n >> k;
initializare();
rezolvare();
return 0;
}