Pagini recente » Cod sursa (job #2950342) | Istoria paginii runda/lab10d22mai2014/clasament | Cod sursa (job #2211925) | Cod sursa (job #1243859) | Cod sursa (job #1348877)
#include <fstream>
using namespace std;
int getRoot(int m[], int x);
void unite(int x, int y, int r[], int m[]);
int main()
{
int N, M, x, y, i, op;
ifstream f("disjoint.in");
f >> N >> M;
int m[N + 1], r[N + 1];
for (i = 1; i <= N; i++)
{
m[i] = i;
r[i] = 1;
}
ofstream g("disjoint.out");
for (i = 1; i <= M; i++)
{
f >> op >> x >> y;
if (op == 1)
unite(x, y, r, m);
else if (op == 2)
{
if (getRoot(m, x) == getRoot(m, y))
g << "DA\n";
else
g << "NU\n";
}
}
f.close();
return 0;
}
int getRoot(int m[], int x)
{
int root = x;
while (m[root] != root)
root = m[root];
int aux;
while(x != m[x])
{
aux = m[x];
m[x] = root;
x = aux;
}
return root;
}
void unite(int x, int y, int r[], int m[])
{
int rootX = getRoot(m, x);
int rootY = getRoot(m, y);
if (r[rootX] >= r[rootY])
m[rootY] = rootX;
else
m[rootX] = rootY;
if (r[rootX] == r[rootY])
r[rootX]++;
}