#805. 【模板】最小瓶颈生成树(数据加强版)
考虑最小瓶颈生成树的性质
因此我们可以直接在最小生成树上求 \(LCA\) 以及 路径上的边的最大值
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template <typename T> void chkmax(T &x, T y) { x = x >= y ? x : y; }
template <typename T> void chkmin(T &x, T y) { x = x <= y ? x : y; }
const int N = 100001, M = 1000001;
struct Edg {
int u, v, w;
bool operator <(const Edg &T) const {
return w < T.w;
}
}edge[M];
int n, m, Q;
int h[N], e[N * 2], ne[N * 2], w[N * 2], idx;
int p[N];
int q[N], dep[N], fa[N][20], mx[N][20];
int find(int x) {
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
}
void bfs(int root) {
memset(dep, 0x3f, sizeof dep);
dep[0] = 0; dep[root] = 1;
int hh = 0, tt = 0; q[0] = root;
while(hh <= tt) {
int t = q[hh ++];
for(int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if(dep[j] <= dep[t] + 1) continue;
dep[j] = dep[t] + 1;
fa[j][0] = t;
mx[j][0] = w[i];
q[++ tt] = j;
for(int k = 1; k < 20; k ++ ) {
fa[j][k] = fa[fa[j][k - 1]][k - 1];
mx[j][k] = max(mx[j][k - 1], mx[fa[j][k - 1]][k - 1]);
}
}
}
}
int lca(int a, int b) {
if(dep[a] < dep[b]) swap(a, b);
for(int k = 19; k >= 0; k -- ) {
if(dep[fa[a][k]] >= dep[b]) {
a = fa[a][k];
}
}
if(a == b) return a;
for(int k = 19; k >= 0; k -- ) {
if(fa[a][k] != fa[b][k]) {
a = fa[a][k];
b = fa[b][k];
}
}
return fa[a][0];
}
int query (int u, int v) {
int res = -1e9;
for(int i = 19; i >= 0; i -- ) {
if(dep[fa[u][i]] >= dep[v]) {
res = max(res, mx[u][i]);
u = fa[u][i];
}
}
return res;
}
void solve() {
scanf("%d%d", &n, &m);
for(int i = 0; i <= n; i ++ ) h[i] = -1, p[i] = i;
for(int i = 0; i < m; i ++ ) {
int u, v, w; scanf("%d%d%d", &u, &v, &w);
edge[i] = {u, v, w};
}
sort(edge, edge + m);
for(int i = 0; i < m; i ++ ) {
int u = edge[i].u, v = edge[i].v, w = edge[i].w;
int fu = find(u), fv = find(v);
if(fu == fv) continue;
add(u, v, w); add(v, u, w);
p[fu] = fv;
}
bfs(1);
scanf("%d", &Q);
while(Q -- ) {
int u, v; scanf("%d%d", &u, &v);
int p = lca(u, v);
printf("%d\n", max(query(u, p), query(v, p)));
}
}
int main() {
solve();
return 0;
}