Pagini recente » Cod sursa (job #2288461) | Cod sursa (job #2902038) | Cod sursa (job #1747416) | Cod sursa (job #767796) | Cod sursa (job #956400)
Cod sursa(job #956400)
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
const int MAXN = 100010;
int uf[MAXN], rank[MAXN];
int find (int x)
{
int representative = x;
for (; representative != uf[representative]; representative = uf[representative]);
int t;
while (x != uf[x])
{
t = x;
x = uf[t];
uf[t] = representative;
}
return representative;
}
void union_find (int x, int y)
{
x = find (x);
y = find (y);
if (rank[x] > rank[y])
uf[y] = x;
else
{
uf[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
int main()
{
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int N, m;
fin >> N >> m;
for (int i = 1; i <= N; ++i)
uf[i] = i;
for (; m; --m)
{
int op, x, y;
fin >> op >> x >> y;
if (op == 1) union_find (x, y);
else if (find(x) == find(y))
fout << "DA\n";
else
fout << "NU\n";
}
fout.close();
return EXIT_SUCCESS;
}