Cod sursa(job #898823)

Utilizator vgabi94Vaduva Gabriel vgabi94 Data 28 februarie 2013 11:52:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#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;
}