Cod sursa(job #991296)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 30 august 2013 11:35:57
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.52 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstdlib>

using namespace std;

#define Nmax 15051
#define Mmax 30003

struct edge
{
    int x;
    int y;
    int c;

} muchii[Mmax];

struct qqq
{
    int x;
    int y;

} query[Nmax];

struct cmp
{
    bool operator() ( const edge &a, const edge &b )
    {
        return a.c > b.c;
    }
};

int rang[Nmax], tata[Nmax], costuri[Nmax];

int N, M, K;

void read()
{
    ifstream f("radiatie.in");

    f >> N >> M >> K;

    for ( int i = 1; i <= M; ++i )
    {
        f >> muchii[i].x >> muchii[i].y >> muchii[i].c;
    }

    for ( int i = 1; i <= K; ++i )
    {
        f >> query[i].x >> query[i].y;
    }

    f.close();
}

void init()
{
    for ( int i = 1; i <= N; ++i )
    {
        tata[i] = i;
    }
}

int Find( int x )
{
    int R;

    for ( R = x; tata[R] != R; R = tata[R] );

    return R;
}

void Union( int x, int y, int cost )
{
    if ( rang[x] > rang[y] )
            tata[y] = x,
            costuri[y] = cost;
    else
            tata[x] = y,
            costuri[x] = cost;

    if ( rang[x] == rang[y] )
            rang[y]++;
}

void Kruskal()
{
    int selected = 0;

    for ( int i = 1; i <= M && selected < N-1; ++i )
    {
        edge cr = muchii[i];

        int x = Find( cr.x );
        int y = Find( cr.y );

        if ( x != y )
        {
            //Union( x, y, cr.c );

            if ( rand()&1 )
                    tata[x] = y,
                    costuri[x] = cr.c;
            else
                    tata[y] = x,
                    costuri[y] = cr.c;

            selected++;
        }
    }

    for ( int i = 1; i <= N; ++i )
            for ( int j = i; j != tata[j]; j = tata[j] )
                    rang[j]++;
}

void interogari()
{
    ofstream g("radiatie.out");

    for ( int i = 1; i <= K; ++i )
    {
        int maxim = -1;
        int a = query[i].x;
        int b = query[i].y;

        for ( ; rang[a] > rang[b] ; a = tata[a] )
                maxim = max( maxim, costuri[a] );

        for ( ; rang[a] < rang[b] ; b = tata[b] )
                maxim = max( maxim, costuri[b] );

        for ( ; a != b; a = tata[a], b = tata[b] )
                maxim = max( maxim, max( costuri[a], costuri[b] ) );


        g << maxim << "\n";
    }

    g.close();
}

int main()
{
    read();
    init();
    sort( muchii + 1, muchii + 1 + M, cmp() );
    Kruskal();
    interogari();

    return 0;
}