Cod sursa(job #1312083)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 8 ianuarie 2015 21:22:04
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.75 kb
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;

ifstream is("radiatie.in");
ofstream os("radiatie.out");

#define DIM 15003
#define fi first
#define se second

int N, M, K, x, y, z, Lev, Solution;
int D[DIM], T[DIM], lg[DIM];
int Height[DIM];
int str[16][DIM], RMQ[16][DIM];
bool B[DIM];
vector <pair<int,int> > G[DIM];
vector <pair<int,int> > Arb[DIM];
priority_queue < pair<int,int> , vector<pair<int,int> > , greater<pair<int,int> > > P;

void Input();
void Prim();
void DFS(int x);
void Query();

int main()
{
    Input();
    Prim();

    memset(B,0,sizeof(B));
    for ( int i = 2; i <= DIM-1; ++i )
        lg[i] = lg[i>>1] + 1;
    Lev = 1;
    Height[1] = 1;
    DFS(1);
    int p, k;
    for ( k = 1, p = 2; p <= (N<<1); k++, p<<=1 )
        for ( int i = 1; i <= N; i++ )
        {
            str[k][i] = str[k-1][str[k-1][i]];
            RMQ[k][i] = max(RMQ[k-1][i],RMQ[k-1][str[k-1][i]]);
        }
    for ( int i = 1; i <= K; ++i )
        Query();
    is.close();
    os.close();
}

void Input()
{
    is >> N >> M >> K;
    for ( int i = 1; i <= M; ++i )
    {
        is >> x >> y >> z;
        G[x].push_back(make_pair(y,z));
        G[y].push_back(make_pair(x,z));
    }
    for ( int i = 2; i <= N; ++i )
        D[i] = 0x3f3f3f3f;
}

void Prim()
{
    int node;
    P.push(make_pair(0,1));
    B[1] = 1;

    while ( !P.empty() )
    {
        node = P.top().se;
        P.pop();

        for ( const auto& v : G[node] )
        {
            if ( !B[v.se] && D[v.fi] > v.se )
            {
                D[v.fi] = v.se;
                T[v.fi] = node;
                P.push(make_pair(v.se,v.fi));
            }
        }

        while ( !P.empty() && !B[P.top().se])
            P.pop();
    }
}

void DFS(int x)
{
    B[x] = 1;

    for ( const auto& v : G[x] )
    {
        if ( !B[v.fi] )
        {
            Lev++;
            Height[v.fi] = Lev;
            str[0][v.fi] = x;
            RMQ[0][v.fi] = v.se;
            DFS(v.fi);
            Lev--;
        }
    }
}

void Query()
{
    Solution = 0;
    is >> x >> y;
    if ( Height[x] < Height[y] )
        swap(x,y);

   for ( int i = lg[Height[x]] ; i >= 0; --i )
    if ( Height[x] - (1<<i) >= Height[y] )
   {
       Solution = max(Solution,RMQ[i][x]);
       x = str[i][x];
   }

   if ( x == y )
   {
       os << Solution << '\n';
       return;
   }

   for ( int i = lg[Height[y]] ; i >= 0; --i )
        if ( str[i][x] != str[i][y] )
        {
            Solution = max(Solution,RMQ[i][x]);
            Solution = max(Solution,RMQ[i][y]);
            x = str[i][x];
            y = str[i][y];
        }
    os << Solution << '\n';
}