Cod sursa(job #830349)

Utilizator ciorile.chioareBogatu Adrian ciorile.chioare Data 6 decembrie 2012 18:15:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
#include<cstdio>

class TreeNode {
        private:
                TreeNode *parent;
        public:
                int isRoot, level;
                TreeNode() {}
                TreeNode(int iset) {
                        isRoot = iset;
                }
                void setParent(TreeNode *parent) {
                        this->parent = parent;
                        this->isRoot = 0;
                }

                TreeNode* root() {
                        return (this->isRoot)?
                                (this):(this->parent->root());
                }
                void compress(TreeNode *root) {
                        if(this == root)
                                return;
                        this->level = 1;
                        TreeNode *aux = this->parent;
                        this->parent = root;
                        aux->compress(root);
                }
};

TreeNode **node;

void _union(int x, int y)
{
        if(node[x]->level < node[y]->level)
                return _union(y, x);
        TreeNode *rootx = node[x]->root();
        TreeNode *rooty = node[y]->root();
        rooty->setParent(rootx);
}

int _find(int x, int y)
{
        TreeNode *rootx = node[x]->root();
        node[x]->compress(rootx);
        TreeNode *rooty = node[y]->root();
        node[y]->compress(rooty);

        if(rootx->isRoot == rooty->isRoot)
                return 1;
        else
                return 0;

}

int main()
{
        int n, m;
        FILE *in = fopen("disjoint.in", "r");
        FILE *out = fopen("disjoint.out", "w");

        fscanf(in, "%d%d", &n, &m);
        node = new TreeNode*[n + 1];
        for(int i = 1; i <= n; ++i)
                node[i] = new TreeNode(i);

        int op, x, y;
        for(int i = 0; i < m; ++i) {
                fscanf(in, "%d%d%d", &op, &x, &y);
                switch(op) {
                        case 1: _union(x, y);
                                break;
                        case 2: switch(_find(x, y)) {
                                        case 0: fprintf(out, "NU\n");
                                                break;
                                        case 1: fprintf(out, "DA\n");
                                                break;
                                }
                                break;
                }
        }
        return 0;
}