Pagini recente » Cod sursa (job #568217) | Cod sursa (job #1046344) | Cod sursa (job #545100) | Cod sursa (job #599405) | Cod sursa (job #1705105)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Tree
{
int parent;
int depth;
Tree(int p, int d) : parent(p), depth(d){
}
};
ifstream in("disjoint.in");
ofstream out("disjoint.out");
vector<Tree> forest;
void swap(int x,int y)
{
int aux= x;
x = y;
y = aux;
}
int find(int x)
{
if (forest[x].parent == -1)
return x;
forest[x].parent = find(forest[x].parent);
return forest[x].parent;
}
void merge(int x, int y)
{
int rootx = find(x);
int rooty = find(y);
if (rootx == rooty)
return;
if (forest[rootx].depth == forest[rooty].depth)
{
forest[rooty].parent = rootx;
forest[rootx].depth++;
return;
}
if (forest[rootx].depth > forest[rooty].depth)
forest[rooty].parent = rootx;
else
forest[rootx].parent = rooty;
}
int main()
{
int n, m;
in >> n >> m;
forest.resize(n+1, Tree(-1, 1));
for (int i = 0; i < m; i++)
{
int op, x, y;
in >> op >> x >> y;
if (op == 1)
merge(x,y);
if (op == 2)
{
if(find(x) == find(y))
out <<"DA\n";
else
out << "NU\n";
}
}
return 0;
}