Pagini recente » Cod sursa (job #2717903) | Cod sursa (job #2356088) | Cod sursa (job #2737458) | Cod sursa (job #1465096) | Cod sursa (job #898823)
Cod sursa(job #898823)
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
const int maxn = 100001;
// Union-Find
struct UF {
UF(int);
void connect(int, int);
bool connected(int, int);
private:
int find(int);
int root[maxn];
int rank[maxn];
};
UF::UF(int n)
{
for (int i = 1; i <= n; i++) {
root[i] = i;
rank[i] = 1;
}
}
int UF::find(int x)
{
if (x != root[x]) root[x] = find(root[x]); // Compresia drumurilor
return root[x];
}
void UF::connect(int p, int q)
{
int pRoot = find(p);
int qRoot = find(q);
if (rank[pRoot] > rank[qRoot]) // Reuniunea dupa rang
root[qRoot] = pRoot;
else {
root[pRoot] = qRoot;
if (rank[pRoot] == rank[qRoot]) rank[qRoot]++;
}
}
bool UF::connected(int p, int q)
{ return find(p) == find(q); }
int main()
{
int N, M, cod, x, y;
in >> N >> M;
UF myset(N);
for (int i = 1; i <= M; i++)
{
in >> cod;
switch(cod)
{
case 1: {
in >> x >> y;
myset.connect(x, y);
} break;
case 2: {
in >> x >> y;
if (myset.connected(x, y)) out << "DA\n";
else out << "NU\n";
} break;
}
}
return 0;
}