Cod sursa(job #2172454)

Utilizator TudorVersoiuVersoiu Tudor Sorin TudorVersoiu Data 15 martie 2018 16:35:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <vector>


using namespace std;
ifstream f("disjoint.in" );
ofstream g("disjoint.out");

struct t_node
{
    int v;
    t_node* father;
};

t_node element[100005];
int n, m;

int inaltime[100005];

int reuniune(int x, int y)
{
    t_node* actX = &element[x];
    t_node* actY = &element[y];

    while ( actX->father != NULL )
        actX = actX->father;
    while ( actY->father != NULL )
        actY = actY->father;

    if ( inaltime[actX->v] < inaltime[actY->v] )
        swap(actX, actY);


    inaltime[actX->v] = max(inaltime[actX->v], inaltime[actY->v] + 1);

    actY->father = actX;
}

int query(int x, int y)
{
    t_node* rootX = &element[x];
    t_node* rootY = &element[y];

    while ( rootX->father != NULL ) rootX = rootX->father;
    while ( rootY->father != NULL ) rootY = rootY->father;

    t_node* actX = &element[x];
    t_node* actY = &element[y];

    while ( actX->father != NULL )
    {
        actX->father = rootX;
        actX = actX->father;
    }
    while ( actY->father != NULL )
    {
        actY->father = rootY;
        actY = actY->father;
    }

    return actX == actY;
}

int main()
{
    f >> n >> m;

    for ( int i=1; i<=n; i++ )
    {
        element[i].v = 1;
        element[i].father = NULL;
    }

    for ( int i=1; i<=m; i++ )
    {
        int tip, x, y;
        f >> tip >> x >> y;

        if ( tip == 1 )
        {
            reuniune(x, y);
        }
        else
        {
            g << (query(x, y)==1?"DA":"NU");
            g << '\n';
        }
    }
}