比赛 中秋节快乐! 评测结果 AAAAAAAAAAAAAAAAAAAA
题目名称 货车运输 最终得分 100
用户昵称 darkMoon 运行时间 1.542 s
代码语言 C++ 内存使用 6.31 MiB
提交时间 2024-09-17 08:34:43
显示代码纯文本
#include<bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define mp make_pair
using namespace std;
auto IN = freopen("truck.in", "r", stdin);
auto OUT = freopen("truck.out", "w", stdout);
auto mread = [](){int x;scanf("%lld", &x);return x;};
const int N = 1e4 + 5;
int n = mread(), m = mread(), fa[N], f[N][25], mi[N][25], d[N];
int findfa(int x){
    if(x == fa[x]){
        return x;
    }
    return fa[x] = findfa(fa[x]);
}
struct node{
    int x, y, z;
}s[5 * N];
vector<pair<int, int> > v[N];
void dfs(int x, int fa){
    d[x] = d[fa] + 1;
    f[x][0] = fa;
    for(int i = 1; i <= 20; i ++){
        f[x][i] = f[f[x][i - 1]][i - 1];
        mi[x][i] = min(mi[x][i - 1], mi[f[x][i - 1]][i - 1]);
    }
    for(auto t : v[x]){
        int y = t.fi;
        if(y == fa){
            continue;
        }
        mi[y][0] = t.se;
        dfs(y, x);
    }
    return;
}
int solve(int x, int y){
    int ans = LONG_LONG_MAX;
    if(d[x] < d[y]){
        swap(x, y);
    }
    if(d[x] > d[y]){
        for(int i = __lg(d[x] - d[y]); i >= 0; i --){
            if(d[f[x][i]] > d[y]){
                ans = min(ans, mi[x][i]);
                x = f[x][i];
            }
        }
        ans = min(ans, mi[x][0]);
        x = f[x][0];
    }
    if(x == y){
        return ans;
    }
    for(int i = __lg(d[x]); i >= 0; i --){
        if(f[x][i] != f[y][i]){
            ans = min({ans, mi[x][i], mi[y][i]});
            x = f[x][i], y = f[y][i];
        }
    }
    ans = min({ans, mi[x][0], mi[y][0]});
    return ans;
}
signed main(){
    for(int i = 1; i <= n; i ++){
        fa[i] = i;
    }
    for(int i = 1; i <= m; i ++){
        cin >> s[i].x >> s[i].y >> s[i].z;
    }
    sort(s + 1, s + 1 + m, [](node a, node b){
        return a.z > b.z;
    });
    for(int i = 1; i <= m; i ++){
        if(findfa(s[i].x) != findfa(s[i].y)){
            fa[findfa(s[i].x)] = findfa(s[i].y);
            v[s[i].x].push_back(mp(s[i].y, s[i].z));
            v[s[i].y].push_back(mp(s[i].x, s[i].z));
        }
    }
    for(int i = 1; i <= n; i ++){
        if(f[i][0] == 0){
            mi[i][0] = LONG_LONG_MAX;
            dfs(i, i);
        }
    }
    int q = mread();
    for(int i = 1, x, y; i <= q; i ++){
        cin >> x >> y;
        if(findfa(x) != findfa(y)){
            printf("-1\n");
        }
        else{
            printf("%lld\n", solve(x, y));
        }
    }
    return 0;
}