Cod sursa(job #2355059)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 25 februarie 2019 19:54:57
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.67 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

struct muchie
{
    int from, to, c;

    bool operator < (const muchie other) const
    {
        return c < other.c;
    }
};

const int MMAX = 30005;
const int NMAX = 15005;
const int LOGMAX = 15;

int N, M, K;

vector <muchie> v;
vector < pair <int, int> > g[NMAX];

int dad[NMAX], rnk[NMAX], h[NMAX];
int st[18][NMAX], cost[18][NMAX];

int Root(int node)
{
    int initNode = node, p = dad[node];

    while(node != p)
    {
        node = p;
        p = dad[p];
    }

    dad[initNode] = p;
    return p;
}

void Join(int node1, int node2)
{
    if(rnk[node1] == rnk[node2])
        rnk[node1]++, dad[node2] = node1;
    else if(rnk[node1] > rnk[node2])
        dad[node2] = node1;
    else
        dad[node1] = node2;
}

void DFS(int node, int dad, int costDad)
{
    st[0][node] = dad;
    cost[0][node] = costDad;
    h[node] = 1 + h[dad];

    for(int i = 1; i <= LOGMAX; i++)
    {
        st[i][node] = st[i - 1][st[i - 1][node]];
        cost[i][node] = max(cost[i - 1][node], cost[i - 1][st[i - 1][node]]);
    }

    for(auto it : g[node])
        if(it.first != dad)
            DFS(it.first, node, it.second);
}

int Query(int x, int y)
{
    int ans = 0;

    if(h[x] < h[y])
        swap(x, y);

    for(int i = LOGMAX; i >= 0; i--)
        if(h[x] - (1 << i) >= h[y])
        {
            ans = max(ans, cost[i][x]);
            x = st[i][x];
        }

    for(int i = LOGMAX; i >= 0; i--)
        if(h[x] > 0 && st[i][x] != st[i][y])
        {
            ans = max(ans, max(cost[i][x], cost[i][y]));
            x = st[i][x];
            y = st[i][y];
        }

    if(x == y)
        return ans;

    return max(ans, max(cost[0][x], cost[0][y]));
}

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

    muchie mch;
    for(int i = 1; i <= M; i++)
    {
        fin >> mch.from >> mch.to >> mch.c;
        v.push_back(mch);
    }

    sort(v.begin(), v.end());

    for(int i = 1; i <= N; i++)
        dad[i] = i;

    for(auto currentMch : v)
    {
        int node1 = currentMch.from;
        int node2 = currentMch.to;

        int p = Root(node1);
        int q = Root(node2);

        if(p != q)
        {
            Join(p, q);
            g[node1].push_back(make_pair(node2, currentMch.c));
            g[node2].push_back(make_pair(node1, currentMch.c));
        }
    }

    DFS(1, 0, 0);

    int x, y;
    for(int i = 1; i <= K; i++)
    {
        fin >> x >> y;
        fout << Query(x, y) << '\n';
    }

    return 0;
}