Cod sursa(job #2425510)

Utilizator turtoieduardEduard Turtoi turtoieduard Data 24 mai 2019 21:09:34
Problema Radiatie Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <fstream>
#include <vector>
#include <algorithm>
#define max3(a, b, c) max(a, max(b, c))
using namespace std;
ifstream fin("radiatie.in");
ofstream fout("radiatie.out");

struct Edge {
    int x, y, cost;
};

bool Comparer(const Edge &a, const Edge &b){
    return a.cost < b.cost;
}

vector<int> father;
vector<int> height;

int getRoot(int node){
    int root = node, y;
    while(root != father[root])
        root = father[root];
    while(node != root){
        y = father[node];
        father[node] = root;
        node = y;
    }
    return root;
}

void Union(int x, int y){
    int rx = getRoot(x);
    int ry = getRoot(y);
    if(height[rx] > height[ry])
        father[ry] = rx;
    else if(height[ry] > height[rx])
        father[rx] = ry;
    else {
        father[ry] = rx;
        height[rx]++;
    }
}

int main(){
    int n, m, k, i, x, y, c;
    vector<Edge> edges;
    fin>>n>>m>>k;
    vector<int> source(n+1, 0);
    vector<int> travel(n+1, 0);
    for(i=0; i<m; i++){
        fin>>x>>y>>c;
        edges.push_back((Edge){x, y, c});
    }
    sort(edges.begin(), edges.end(), Comparer);
    height.assign(n+1, 0);
    father.resize(n+1);
    for(i=1; i<=n; i++)
        father[i] = i;
    int pos = 0, selected = 0;
    while(pos < m && selected < n-1){
        int left = edges[pos].x;
        int right = edges[pos].y;
        int cost = edges[pos].cost;
        pos++;
        if(getRoot(left) != getRoot(right)){
            selected++;
            Union(left, right);
            travel[right] = cost;
            source[right] = left;
        }
    }
    for(i=1; i<=k; i++){
        fin>>x>>y;
        vector<int> dmaxx(n+1, 0);
        vector<int> dmaxy(n+1, 0);
        int curr = x;
        while(source[curr] != 0){
            dmaxx[source[curr]] = max(dmaxx[curr], travel[curr]);
            curr = source[curr];
        }
        curr = y;
        while(father[curr] != 0){
            dmaxy[source[curr]] = max(dmaxy[curr], travel[curr]);
            curr = source[curr];
        }
        int best = 0;
        for(int j=1; j<=n; j++)
            if(dmaxx[j] == 0 || dmaxy[j] ==0)
                best = max3(best, dmaxx[j], dmaxy[j]);
        fout<<best<<endl;
    }
    return 0;
}