Cod sursa(job #991293)

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

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;
        rang[i] = 1;
    }
}

int Find( int x )
{
    int y, 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, m = M;

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

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

        if ( x != y )
        {
            Union( x, y, cr.c );
            selected++;
        }
    }
}

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]; a = tata[a] )
                maxim = max( maxim, costuri[a] );

        for ( ; rang[a] < rang[b] && b != tata[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();
    make_heap( muchii + 1, muchii + 1 + M, cmp() );
    Kruskal();
    interogari();

    return 0;
}