Pagini recente » Cod sursa (job #394397) | Cod sursa (job #1849057) | Cod sursa (job #3256440) | Cod sursa (job #60774) | Cod sursa (job #1110221)
#include <fstream>
#include <vector>
using namespace std;
class DisjointSets {
public:
static const int NIL = -1;
DisjointSets(const int size = 0):
father(vector<int>(size, NIL)),
rank(vector<int>(size, 0)) {}
int Size() const {
return int(father.size());
}
int Find(const int x) {
if (father[x] == NIL)
return x;
return father[x] = Find(father[x]);
}
bool Merge(int x, int y) {
x = Find(x);
y = Find(y);
if (x == y)
return false;
if (rank[x] < rank[y])
swap(x, y);
father[y] = x;
rank[x] = max(rank[x], rank[y] + 1);
return true;
}
private:
vector<int> father, rank;
};
int main() {
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int n, q;
cin >> n >> q;
DisjointSets sets = DisjointSets(n);
for (; q > 0; --q) {
int type;
cin >> type;
if (type == 1) {
int x, y;
cin >> x >> y;
sets.Merge(--x, --y);
} else {
int x, y;
cin >> x >> y;
if (sets.Find(--x) == sets.Find(--y))
cout << "DA\n";
else
cout << "NU\n";
}
}
cin.close();
cout.close();
return 0;
}