Cod sursa(job #2425578)

Utilizator turtoieduardEduard Turtoi turtoieduard Data 24 mai 2019 21:47:38
Problema Radiatie Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.05 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 cx = x;
        while(source[x] != 0 ){
            dmaxx[source[x]] = max(dmaxx[x], travel[x]);
            x = source[x];
        }
        while(source[y] != 0){
            if(dmaxx[y] != 0 || y == cx)
                break;
            dmaxy[source[y]] = max(dmaxy[y], travel[y]); 
            y = source[y];
        }
        fout<<max(dmaxy[y], dmaxx[y])<<endl;
    }
    return 0;
}