Pagini recente » Cod sursa (job #2070367) | Cod sursa (job #2602309) | Cod sursa (job #1593272) | Cod sursa (job #2907824) | Cod sursa (job #2807605)
#include <bits/stdc++.h>
using namespace std;
int N, M, cod, x, y;
struct Forest
{
int parent, size;
};
vector<Forest> makeForest(const int& N)
{
vector<Forest> F(N + 1);
for (int i = 1; i <= N; ++i)
{
F[i].parent = i;
F[i].size = 1;
}
return F;
}
int findParent(int x, vector<Forest>& F)
{
while (F[x].parent != x)
{
F[x].parent = F[ F[x].parent].parent;
F[x].size = F[F[x].parent].size;
x = F[x].parent;
}
return x;
}
void unionForest(int x, int y, vector<Forest>& F)
{
x = findParent(x, F);
y = findParent(y, F);
if (x == y) return;
if (F[x].size > F[y].size)
{
F[y].parent = x;
F[x].size += F[y].size;
}
else
{
F[x].parent = y;
F[x].size += F[x].size;
}
}
bool checkForest(int x, int y, vector<Forest>& F)
{
if (findParent(x, F) == findParent(y, F))
return 1;
return 0;
}
int main()
{
ifstream in("disjoint.in");
ofstream out("disjoint.out");
in >> N >> M;
vector<Forest> f = makeForest(N);
while (M)
{
M--;
in >> cod >> x >> y;
if (cod == 1) unionForest(x, y, f);
if (cod == 2) checkForest(x, y, f) ? out<<"DA\n" : out <<"NU\n";
}
in.close();
out.close();
return 0;
}