Pagini recente » Monitorul de evaluare | Mozaic | Cod sursa (job #2001943) | Monitorul de evaluare | Cod sursa (job #2247386)
#include <fstream>
#include <vector>
using namespace std;
class Sets
{
public:
Sets(int n) : fathers_(vector<int>(n, -1)) {}
void Unite(int a, int b);
bool SameGroup(int a, int b);
private:
vector<int> fathers_;
int get_root(int node);
};
void Sets::Unite(int a, int b)
{
auto root_a = get_root(a);
auto root_b = get_root(b);
if (root_a != root_b) {
fathers_[root_b] = root_a;
}
}
bool Sets::SameGroup(int a, int b)
{
return get_root(a) == get_root(b);
}
int Sets::get_root(int node)
{
if (fathers_[node] == -1) {
return node;
}
return fathers_[node] = get_root(fathers_[node]);
}
int main()
{
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n, queries;
fin >> n >> queries;
Sets sets(n);
for (int i = 0; i < queries; i += 1) {
int type, a, b;
fin >> type >> a >> b;
if (type == 1) {
sets.Unite(a - 1, b - 1);
} else {
fout << (sets.SameGroup(a - 1, b - 1) ? "DA" : "NU") << "\n";
}
}
return 0;
}