Cod sursa(job #934352)

Utilizator whoasdas dasdas who Data 30 martie 2013 15:39:27
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>

using namespace std;

struct node {
    int data;
    node *parent;
    int rank;
    node(int x) {
        data = x;
        parent = NULL;
        rank = 0;
    }
};

node* rep(node** nodes, int x)
{
    node* n = nodes[x];
    while (n->parent != NULL)
        n = n->parent;
    /* flattening optimization */
    node *r = n, *p;
    n = nodes[x];
    while (n->parent != NULL) {
        p = n->parent;
        n->parent = r;
        n = p;
    }
    return r;
}

void unite(node** nodes, int x, int y)
{
    node *repx, *repy;
    repx = rep(nodes, x);
    repy = rep(nodes, y);

    if (repx->rank > repy->rank) {
        repy->parent = repx;
    } else if (repx->rank < repy->rank) {
        repx->parent = repy;
    } else {
        repx->parent = repy;
        repy->rank++;
    }
}



int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");
    int n, m;
    in>>n>>m;
    node *nodes[n];
    for (int i = 0; i < n; i++)
        nodes[i] = new node(i);

    int op, x, y;
    while (m-->0) {
        in>>op>>x>>y;
        x--; y--;
        switch (op) {
            case 1:
                unite(nodes, x, y);
                break;
            case 2:
                if (rep(nodes, x) == rep(nodes, y))
                    out<<"DA"<<endl;
                else
                    out<<"NU"<<endl;
                break;
        }
    }
    return 0;
}