Pagini recente » Cod sursa (job #2440182) | Cod sursa (job #1735262) | Cod sursa (job #1490092) | Cod sursa (job #980436) | Cod sursa (job #2807597)
#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);
for (int i = 1; i <= N; ++i)
{
F[i].parent = i;
F[i].size = 1;
}
return F;
}
int findParent(int x, const vector<Forest>& F)
{
int parent = F[x].parent;
while (parent != x)
{
parent = F[parent].parent;
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, const 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;
}