Pagini recente » Cod sursa (job #2067042) | Cod sursa (job #1028463) | Cod sursa (job #1665374) | Cod sursa (job #1409324) | Cod sursa (job #2979045)
#include <iostream>
#include <fstream>
using namespace std;
const int NMAX = 100005;
int n, m, x, y, code, parent[NMAX];
/// we need to find the root of a tree
int findRoot(int node) {
if (!parent[node]) {
return node;
}
return findRoot(parent[node]);
}
/// we need to unite two trees
void uniteTrees(int node1, int node2) {
int node1Root = findRoot(node1), node2Root = findRoot(node2);
/*
cout << "x: " << node1 << endl;
cout << "y: " << node2 << endl;
cout << "Root of x: " << node1Root << endl;
cout << "Root of y: " << node2Root << endl;
*/
if (node1Root != node2Root) {
parent[node1Root] = node2Root;
}
}
int main() {
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
fin >> n >> m;
for (int i = 0; i < m; ++i) {
fin >> code >> x >> y;
if (code == 1) {
parent[x] = y;
uniteTrees(x, y);
} else {
if (findRoot(x) == findRoot(y)) {
fout << "DA\n";
} else {
fout << "NU\n";
}
}
/*
for (int j = 1; j <= n; ++j) {
cout << parent[j] << ' ';
}
cout << endl << endl;
*/
}
/*
for (int i = 1; i <= m; ++i) {
fin >> x >> y;
parent[x] = y;
}
*/
for (int i = 1; i <= n; ++i) {
cout << "Root of node " << i << ": " << findRoot(i) << endl;
}
return 0;
}