Pagini recente » Cod sursa (job #1830347) | Cod sursa (job #1725792) | Cod sursa (job #2980814) | Cod sursa (job #2775749) | Cod sursa (job #2983196)
#include <fstream>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int t[100001], rang[100001];
int get_root(int node)
{
int aux = node;
while (t[node] > 0)
node = t[node];
int root = node;
// mai parcurg odata acelasi drum si unesc nodurile de root
node = aux;
while (node != root)
{
aux = t[node];
t[node] = root;
node = aux;
}
return root;
}
int querry(int x, int y)
{
return get_root(x) == get_root(y);
}
void join(int x, int y)
{
int root_x = get_root(x); // radacina arborelui lui x
int root_y = get_root(y); // radacina arborelui lui y
if (root_x == root_y) // sunt deja in acelasi arbore
return;
if (t[root_x] <= t[root_y])
{ // arborele lui x are mai multe noduri
t[root_x] += t[root_y];
t[root_y] = root_x; // legam arborele lui y de arborele lui x
}
else
{
t[root_y] += t[root_x];
t[root_x] = root_y; // legam arborele lui x de arborele lui y
}
}
int main()
{
int n, m, i, op, x, y, k = 1;
cin >> n >> m;
for (i = 1; i <= m; ++i)
{
cin >> op >> x >> y;
if (op == 1)
join(x, y);
else
{
if (querry(x, y))
cout << "DA" << '\n';
else
cout << "NU" << '\n';
}
}
return 0;
}