Cod sursa(job #1755347)

Utilizator sulzandreiandrei sulzandrei Data 9 septembrie 2016 21:43:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");

////////////////////////
///////////
///////////       Disjoint Set folosind liste inlantuite
///////////
///////////////////////
template < class T = int >
struct Node
{
    T value;
    int rang;
    Node<T>* rep,*next,*last;
    Node(T v,int r):value(v),rang(r){rep = last = this; next= nullptr;}
};
Node<int>* nodes[100003];
void FormSet(int i)
{
    nodes[i] = new Node<int>(i,0);
}
void Union(Node<int>* &x, Node<int>* &y)
{
    if(x->rang > y->rang)
    {
        x->last->next = y;
        y->rep = x;
        x->last = y->last;
    }
    else
    {
        y->last->next = x;
        x->rep = y;
        y->last = x->last;
    }
    if(x->rang == y->rang)
        y->rang++;
}
Node<int>* & Head(Node<int>* &x)
{
    //varianta rapida
    Node<int>* &tata = x,*y;
    while(tata->value != tata->rep->value)
        tata = tata->rep;
    while(x->value != x->rep->value)
    {
        y = x->rep, x->rep = tata, x = y;
    }
    return x;
    //varianta usoara
    /*
     if(x->value != x->rep->value)
        x->rep = Head(x->rep);
     return x->rep;
     */
}
void Reunion(Node<int>* &x, Node<int>* &y)
{
    Union(Head(x),Head(y));
}
int main()
{
    int n,m,op,x,y;
    in >> n >> m;
    //for(int i = 1 ; i <= n ; i ++)
      //  FormeazaMultime(i);
    for(int i = 1 ; i <= n ; i++)
        FormSet(i);
    while(m--)
    {
        in >> op >> x >> y;
        switch(op)
        {
            case 1:
                //Reuneste(x,y);
                Reunion(nodes[x],nodes[y]);
                break;
            case 2: if //(GasesteMultime(x) == GasesteMultime(y))
                        (Head(nodes[x])->value == Head(nodes[y])->value)
                        out<<"DA\n";
                    else
                        out<<"NU\n";
                    break;
        }
    }
    return 0;
}