哪里错了啊...

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#define MAXN 10000 + 10
#define MAXM 50000 + 10
#define MAX_LOG_N 20
using namespace std;
const int inf = 0x3f3f3f3f;
const int ub = 1e5 + 7;
int V, E, Q;
struct edge {
    int u, v, cost;
};
struct node {
    int to, cost;
    node(int to, int cost): to(to), cost(cost) {}
};
edge es[MAXM];
vector<node> G[MAXM];
int par[MAXN], vis[MAXN], depth[MAXN], far[MAXN][MAX_LOG_N + 2], f[MAXN][MAX_LOG_N + 2];
int find(int x) {
    if(par[x] == x) return x;
    else return par[x] = find(par[x]);
}
bool same(int x, int y) {
    return find(x) == find(y);
}
void unite(int x, int y) {
    x = find(x);
    y = find(y);
    par[y] = x;
}
void add_edge(int u, int v, int cost) {
    G[u].push_back(node(v, cost));
    G[v].push_back(node(u, cost));
}
bool comp(const edge& e1, const edge& e2) {
    return e1.cost > e2.cost;
}
void dfs(int u, int v, int d) {
    vis[u] = 1;
    depth[u] = d;
    far[u][0] = v;
    for (int i = 0; i < G[u].size(); i++) {
        if(G[u][i].to != v) {
            f[G[u][i].to][0] = G[u][i].cost;
            dfs(G[u][i].to, u, d + 1);
        }
    }
}
void solve() {
    sort(es, es + E, comp);
    for (int i = 0; i < E; i++) {
        edge e = es[i];
        if(!same(e.u, e.v)) {
            unite(e.u, e.v);
            add_edge(e.u, e.v, e.cost);
        }
    }
    for (int i = 0; i < V; i++) {
        if(!vis[i]) dfs(i, -1, 0);
    }
    for(int i = 1; i <= MAX_LOG_N; i++)
        for(int j = 1; j <= V; j++)
            far[j][i] = far[far[j][i - 1]][i - 1], f[j][i] = min(f[j][i - 1], f[far[j][i - 1]][i - 1]);
}
int search(int x, int y) {
    if(!same(x, y)) return -1;
    if(depth[x] < depth[y]) swap(x, y);
    int d = depth[x] - depth[y];
    int minw = inf;
    if(d > 0)
        for(int k = 0; k <= MAX_LOG_N; k++)
            if(d >> k & 1) {
                minw = min(minw, f[x][k]);
                x = far[x][k];
            }
    if(x == y)    return minw;
    for(int k = MAX_LOG_N; k >= 0; k--) {
        if(far[x][k] != far[y][k]) {
            minw = min(minw, min(f[x][k], f[y][k]));
            x = far[x][k];
            y = far[y][k];
        }
    }
    minw = min(f[x][0], f[y][0]);
    return minw;
}
void init() {
    cin >> V >> E;
    for (int i = 1, a, b, c; i <= E; i++) {
        scanf("%d%d%d", &a, &b, &c);
        es[i].u = a;
        es[i].v = b;
        es[i].cost = c;
    }
    for (int i = 1; i <= V; i++) {
        par[i] = i;
    }
    solve();
    cin >> Q;
    for (int i = 1, u, v; i <= Q; i++) {
        scanf("%d%d", &u , &v);
        cout << search(u, v) << endl;
    }
}
int main() {
// freopen("test.in", "r", stdin);
    init();
    return 0;
}

0 条评论

目前还没有评论...

信息

ID
1843
难度
7
分类
(无)
标签
递交数
5319
已通过
954
通过率
18%
被复制
10
上传者