Cod sursa(job #1771672)

Utilizator CiurezAndreiCiurez Marius-Andrei CiurezAndrei Data 5 octombrie 2016 21:00:51
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.58 kb
#include <bits/stdc++.h>


using namespace std;

ifstream fin("radiatie.in");
ofstream fout("radiatie.out");

int index, N, M, K, x, y;
int niv[30010], T[30010];
pair<int, int> T2[30010];
vector< pair<int, int> > L[15010];
queue <int> Q;
bitset<15010>viz;

struct muchie
{
    int a, b;
    int cost;
} v[30010];

inline void queueClear( queue<int> &Q)
{
    queue<int> Empty;
    swap(Q, Empty);
}

inline bool cmp(const muchie &x, const muchie &y)
{
    return x.cost < y.cost;
}

inline void join(int x, int y)
{
    while(T[x] > 0)
    {
        Q.push(x);
        x = T[x];
    }
    while(T[y] > 0)
    {
        Q.push(y);
        y = T[y];
    }

    if(x == y)
    {
        queueClear(Q);
        return;
    }

    if(T[x] <= T[y])
    {
        T[x] += T[y];
        T[y] = x;

        while(!Q.empty())
        {
            T[Q.front()] = x;
            Q.pop();
        }
    }
    else
    {
        T[y] += T[x];
        T[x] = y;

        while(!Q.empty())
        {
            T[Q.front()] = y;
            Q.pop();
        }
    }

    L[ v[index].a ].push_back(make_pair(v[index].b, v[index].cost));
    L[ v[index].b ].push_back(make_pair(v[index].a, v[index].cost));

}

inline void dfs(const int &node, const int &level)
{
    viz[node] = 1;
    niv[node] = level;

    for(int i = 0; i < L[node].size(); i ++)
    {
        if(viz[ L[node][i].first ] == 0 )
        {
            T2[ L[node][i].first ] = make_pair(node, L[node][i].second);
            dfs(L[node][i].first, level + 1);
        }
    }
}

int main()
{
    fin >> N >> M >> K;

    for(int i = 1; i <= M; i ++)
    {
        fin >> v[i].a >> v[i].b  >> v[i].cost;
    }

    sort(v + 1, v + M + 1, cmp);

    for(int i = 1; i <= N; i ++)
    {
        T[i] = -1;
    }

    for(index = 1; index <= M; index ++)
    {
        join(v[index].a, v[index]. b);
    }

    dfs(1, 0);

    for(int i = 1; i <= K; i ++)
    {
        fin >> x >> y;

        long long solution = 0;

        while(x != y)
        {
            if(niv[x] > niv[y])
            {
                if(T2[x].second > solution)
                {
                    solution = T2[x].second;
                }
                x = T2[x].first;
            }
            else
            {
                if(T2[y].second > solution)
                {
                    solution = T2[y].second;
                }
                y = T2[y].first;
            }
        }

        fout << solution << '\n';

    }

    return 0;
}