Pagini recente » Cod sursa (job #3150590) | Diferente pentru utilizator/tvlad intre reviziile 32 si 20 | Profil vladstoick | Profil AndrewTheGreat | Cod sursa (job #3129277)
#include <fstream>
#include <vector>
using namespace std;
class DisjointSet {
public:
DisjointSet(int nodes) : parent_(nodes, -1) {
}
int Root(int node) {
if (parent_[node] == -1) {
return node;
}
return parent_[node] = Root(parent_[node]);
}
void Unite(int a, int b) {
auto root_a = Root(a);
auto root_b = Root(b);
if (root_a != root_b) {
parent_[root_b] = root_a;
}
}
private:
vector<int> parent_;
};
int main() {
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int nodes, queries;
fin >> nodes >> queries;
auto dset = DisjointSet(nodes);
for (int i = 0; i < queries; i += 1) {
int type, x, y;
fin >> type >> x >> y;
if (type == 1) {
dset.Unite(x - 1, y - 1);
} else if (type == 2) {
auto res = dset.Root(x - 1) == dset.Root(y - 1);
fout << (res ? "DA" : "NU") << "\n";
}
}
return 0;
}