题意:给出n个顶点m条边,每条边一个危险系数,从u到v的危险系数为所经过的道路的最大的危险系数,给出q个u 到v的查询,问u->v的最大危险系数最小是多少
思路:很明显最小瓶颈路,先找出最小生成树,然后以1为根节点生成一棵有向树,再ST算法预处理找最近公共祖先,查询的时候就易于处理了
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstdlib>
const int maxn = 5 * 1e4 + 10;
const int INF = 1e9 + 10;
using namespace std;
struct P {
int u, v, d;
P() {}
P(int u, int v, int d) : u(u), v(v), d(d) {}
} g[2 * maxn];
vector<P> G[maxn];
int n, m, q, T = 0;
int from, to, dis;
int r[maxn], p[maxn], pre[maxn];
int anc[maxn][60], cost[maxn][60];
int c[maxn], deep[maxn];
bool operator < (P a, P b) {
return a.d < b.d;
}
void init() {
memset(deep, 0, sizeof(deep));
for(int i = 0; i < maxn; i++) {
G[i].clear();
pre[i] = i;
r[i] = 0;
}
}
int found(int x) {
if(x == pre[x]) return x;
return pre[x] = found(pre[x]);
}
bool same(int x, int y) { return found(x) == found(y); }
void unit(int x, int y) {
int nx = found(x), ny = found(y);
if(nx == ny) return ;
if(r[nx] < r[ny]) pre[nx] = ny;
else {
pre[ny] = nx;
if(r[nx] == r[ny]) r[nx]++;
}
}
void dfs(int x, int f, int l) {
deep[x] = l; p[x] = f;
for(int i = 0; i < G[x].size(); i++) {
int v = G[x][i].v;
if(v == f) continue;
c[v] = G[x][i].d;
dfs(v, x, l + 1);
}
}
void preprocess() {
for(int i = 1; i <= n; i++) {
anc[i][0] = p[i]; cost[i][0] = c[i];
for(int j = 1; (1 << j) < n; j++) anc[i][j] = -1;
}
for(int j = 1; (1 << j) < n; j++) {
for(int i = 1; i <= n; i++) {
if(anc[i][j - 1] == -1) continue;
int a = anc[i][j - 1];
anc[i][j] = anc[a][j - 1];
cost[i][j] = max(cost[i][j - 1], cost[a][j - 1]);
}
}
}
int query(int p, int q) {
int lg;
if(deep[p] < deep[q]) swap(p, q);
for(lg = 1; (1 << lg) <= deep[p]; lg++); lg--;
int ans = 0;
for(int i = lg; i >= 0; i--) {
if(deep[p] - (1 << i) >= deep[q]) {
ans = max(ans, cost[p][i]); p = anc[p][i];
}
}
if(p == q) return ans;
for(int i = lg; i >= 0; i--) {
if(anc[p][i] != -1 && anc[p][i] != anc[q][i]) {
ans = max(ans, cost[p][i]); p = anc[p][i];
ans = max(ans, cost[q][i]); q = anc[q][i];
}
}
ans = max(ans, max(c[p], c[q]));
return ans;
}
int main() {
int tt = 0;
while(scanf("%d %d", &n, &m) != EOF) {
if(tt++) puts("");
init();
for(int i = 0; i < m; i++) {
scanf("%d %d %d", &from, &to, &dis);
g[i] = P(from, to, dis);
}
sort(g, g + m);
int cnt = 0;
for(int i = 0; i < m; i++) {
from = g[i].u; to = g[i].v;
if(same(from, to)) continue;
unit(from, to); cnt++;
G[from].push_back(P(from, to, g[i].d));
G[ to ].push_back(P(to, from, g[i].d));
if(cnt == n - 1) break;
}
dfs(1, -1, 0); p[1] = -1;
preprocess();
scanf("%d", &q);
while(q--) {
scanf("%d %d", &from, &to);
printf("%d\n", query(from, to));
}
}
return 0;
}