Cod sursa(job #1234525)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 27 septembrie 2014 15:17:05
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 100000 + 2;

int Left[Nmax], Right[Nmax], Parent[Nmax];

bool isRoot( int p )
{
    return ( !Parent[p] || ( Left[ Parent[p] ] != p && Right[ Parent[p] ] != p ) );
}

 void connect(int ch, int p, bool leftChild) {
		if (leftChild)
			Left[p] = ch;
		else
			Right[p] = ch;
		if (ch != 0)
			Parent[ch] = p;
	}

	 void rotate(int x) {
		int p = Parent[x];
		int g = Parent[p];
		bool isRootP = isRoot(p);
		bool leftChildX = (x == Left[p]);

		connect(leftChildX ? Right[x] : Left[x], p, leftChildX);
		connect(p, x, !leftChildX);

		if (!isRootP)
			connect(x, g, p == Left[g]);
		else
			Parent[x] = g;
	}

	 void splay(int x) {
		while (!isRoot(x)) {
			int p = Parent[x];
			int g = Parent[p];
			if (isRoot(p)) {
				// zig
				rotate(x);
			} else if ((x == Left[p]) == (p == Left[g])) {
				// zig-zig
				rotate(p);
				rotate(x);
			} else {
				// zig-zag
				rotate(x);
				rotate(x);
			}
		}
	}

int expose( int p )
{
    int last = 0;

    for ( int x = p; x != 0; x = Parent[x] )
    {
        splay( x );
        Left[x] = last;
        last = x;
    }

    splay( p );

    return last;
}

int findRoot( int p )
{
    expose( p );

    while ( Right[p] != 0 ) p = Right[p];

    return p;
}

void link( int x, int y )
{
    expose( x );
    Parent[x] = y;
}

void cut( int x, int y )
{
    expose( x );
    Parent[ Right[x] ] = 0;
    Right[x] = 0;
}

void afis()
{
    for ( int i = 1; i <= 5; ++i )
    {
        cout << i << ": " << Left[i] << " " << Right[i] << " " << Parent[i] << endl;
    }
}

int N, M;

int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    in >> N >> M;

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

        if ( tip == 1 )
            link( x, y );
        else
        {
            if ( findRoot( x ) == findRoot( y ) )
                out << "DA\n";
            else
                out << "NU\n";
        }
    }

    ///afis();

    return 0;
}