先考虑建最大生成树,但单次查询复杂度O(n),于是用LCA的O(nlogn)预处理一下
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f
const int maxn = 10000 + 10;
const int maxm = 50000 + 10;
int n, m, q, head[maxn], f[maxn], tot;
int fa[maxn][16], w[maxn][16], dep[maxn], rt, t;
struct Edge {
int x, y, w;
} e[maxm];
struct node {
int to, next, val;
} tree[maxm << 1];
inline bool cmp(Edge a, Edge b) { return a.w > b.w; }
inline void add(int x, int y, int w) {
tree[++tot].to = y;
tree[tot].val = w;
tree[tot].next = head[x];
head[x] = tot;
}
int find(int x) {
if (x != f[x])
f[x] = find(f[x]);
return f[x];
}
inline void Kruskal() {
for (int i = 1; i <= n; i++) f[i] = i;
sort(e + 1, e + m + 1, cmp);
int ans = 0;
for (int i = 1; i <= m; i++) {
int a = find(e[i].x), b = find(e[i].y);
if (a != b) {
f[a] = b;
ans++;
add(e[i].x, e[i].y, e[i].w);
add(e[i].y, e[i].x, e[i].w);
}
}
}
void dfs(int x, int pre, int val) {
dep[x] = dep[pre] + 1;
w[x][0] = val;
fa[x][0] = pre;
for (int i = 1; i <= t; i++) {
fa[x][i] = fa[fa[x][i - 1]][i - 1];
w[x][i] = min(w[x][i - 1], w[fa[x][i - 1]][i - 1]);
}
for (int i = head[x]; i; i = tree[i].next) {
if (tree[i].to != pre) {
dfs(tree[i].to, x, tree[i].val);
}
}
}
inline int LCA(int x, int y) {
if (dep[x] < dep[y])
swap(x, y);
int ans = INF;
for (int i = t; i >= 0; i--)
if (dep[fa[x][i]] >= dep[y]) {
ans = min(ans, w[x][i]);
x = fa[x][i];
}
if (x == y)
return ans;
for (int i = t; i >= 0; i--)
if (fa[x][i] != fa[y][i]) {
ans = min(ans, min(w[x][i], w[y][i]));
x = fa[x][i], y = fa[y][i];
}
int val = w[x][0];
if (fa[x][0] != y)
val = min(val, w[y][0]);
return min(ans, val);
}
int main() {
memset(fa, INF, sizeof(fa));
memset(w, INF, sizeof(w));
scanf("%d%d", &n, &m);
t = log2(n) + 1;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].w);
}
Kruskal();
for (int i = 1; i <= n; i++)
if (i == f[i])
dfs(i, i, INF);
scanf("%d", &q);
while (q--) {
int x, y;
scanf("%d%d", &x, &y);
if (find(x) != find(y))
printf("-1\n");
else
printf("%d\n", LCA(x, y));
}
return 0;
}