Pagini recente » Cod sursa (job #2670617) | Cod sursa (job #1594190) | Cod sursa (job #2297418) | Cod sursa (job #1533442) | Cod sursa (job #2822006)
#include <bits/stdc++.h>
using namespace std;
class Forest
{
private:
int parent, size;
public:
static 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;
}
static 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;
}
static 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;
}
}
static 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");
int N, M;
in >> N >> M;
vector<Forest> f = Forest::makeForest(N);
int x, y, cod;
ofstream out("disjoint.out");
while (M)
{
M--;
in >> cod >> x >> y;
if (cod == 1) Forest::unionForest(x, y, f);
if (cod == 2)
{
if (Forest::checkForest(x,y,f) == 1)
out << "DA\n";
else out << "NU\n";
}
}
out.close();
}