Cod sursa(job #934311)

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

using namespace std;

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

int rep(node** nodes, int x)
{
    while (nodes[x]->parent != NULL)
        x = nodes[x]->parent->data;
    return x;
}

void unite(node** nodes, int x, int y)
{
    nodes[rep(nodes, x)]->parent = nodes[rep(nodes, y)];
}



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;
}