Pagini recente » Cod sursa (job #1442556) | Arhiva de probleme | Cod sursa (job #855554) | Istoria paginii runda/nopainnogain | Cod sursa (job #2009919)
#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 root, int node) {
_root[node] = root;
for (auto x : _node[node]) {
if (_root[x] == root)
continue;
_ch_root(root, x);
}
}
void _link(int x, int y) {
if (_size[_root[x]] < _size[_root[y]])
swap(x, y);
_size[_root[x]] += _size[_root[y]];
_node[_root[x]].push_back(_root[y]);
_ch_root(_root[x], _root[y]);
}
};
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);
}
}
}