Pagini recente » Cod sursa (job #1293974) | Cod sursa (job #36064) | Cod sursa (job #332324) | Monitorul de evaluare | Cod sursa (job #2009657)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
class Graph {
public:
Graph(int n) {
this -> n = n;
_node.resize(n + 1);
_root.resize(n + 1);
_size.resize(n + 1);
for (int i = 1; i <= n; i ++) {
_size[i] = 1;
_root[i] = i;
}
}
void link(int x, int y) {
_link(x, y);
}
void query(int x, int y) {
_root[x] == _root[y] ? cout << "DA" << '\n' : cout << "NU" << '\n';
}
private:
int n;
vector < vector < int > > _node;
vector < int > _size;
vector < int > _root;
void ch_root(int r, int y) {
_root[y] = r;
for (int el : _node[y]) {
if (_root[el] == r)
continue;
ch_root(r, el);
}
}
void _link(int x, int y) {
if (_size[_root[x]] >= _size[_root[y]]) {
_node[x].push_back(_root[y]);
ch_root(_root[x], _root[y]);
_size[_root[x]] += _size[_root[y]];
}
else {
_node[_root[y]].push_back(_root[x]);
ch_root(_root[y], _root[x]);
_size[_root[y]] += _size[_root[x]];
}
}
};
int main() {
int n, m;
cin >> n >> m;
Graph *graph = new Graph(n);
for (int i = 1; i <= m; i ++) {
int type;
cin >> type;
if (type == 1) {
int x, y;
cin >> x >> y;
graph -> link(x, y);
}
else {
int x, y;
cin >> x >> y;
graph -> query(x, y);
}
}
}