题意:A国有n座城市,编号从 1到n,城市之间有 m 条双向道路。每一条道路对车辆都有重量限制,简称限重。现在有 q 辆货车在运输货物, 司机们想知道每辆车在不超过车辆限重的情况下,最多能运多重的货物。给出路和城市。
思路:对此图建立最大生成树,然后要求两个城市的最大货物运载量,就是求LCA和路的最小值。
#include
#define ll long long
using namespace std;
const int N = 5e4 + 10;
int q, n, m, d[N], h[N << 1], cnt, f[N][21], dep[N], vis[N], w[N][21];
struct ed {
int u, v, w;
} e[50005]; //题目所给的图
struct no {
int v, w, net;
} no[100005]; //最大生成树的图
bool CMP(ed x, ed y) {
return x.w > y.w; //将边权从大到小排序
}
int F(int x) { //并查集寻找父节点
if(d[x] != x)
d[x] = F(d[x]);
return d[x];
}
void add(int u, int v, int w) {
no[++cnt].net = h[u];
no[cnt].v = v;
no[cnt].w = w;
h[u] = cnt;
}
void dfs(int u, int fa) {
dep[u] = dep[fa] + 1;
vis[u] = 1;
for(int i = 1; i <= 20; i++) {
f[u][i] = f[f[u][i - 1]][i - 1];
w[u][i] = min(w[f[u][i - 1]][i - 1], w[u][i - 1]);
}
for(int i = h[u]; ~i; i = no[i].net) {
int v = no[i].v;
if(!vis[v]) {
f[v][0] = u;
w[v][0] = no[i].w;
dfs(v, u);
}
}
}
int lca(int x, int y) {
if(F(x) != F(y))
return -1;
int ans = 1e9;
if(dep[x] < dep[y])
swap(x, y);
for(int i = 20; i >= 0; i--)
if(dep[f[x][i]] >= dep[y]) {
ans = min(ans, w[x][i]);
x = f[x][i];
if(x == y)
return ans;
}
for(int i = 20; i >= 0; i--)
if(f[x][i] != f[y][i]) {
ans = min(ans, min(w[x][i], w[y][i]));
x = f[x][i];
y = f[y][i];
}
return min(ans, min(w[x][0], w[y][0]));
}
int main() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++)
d[i] = i;
for(int i = 1; i <= m; i++)
scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);
sort(e + 1, e + m + 1, CMP);
memset(h, -1, sizeof h);
for(int i = 1; i <= m; i++) {
int x = F(e[i].u), y = F(e[i].v);
if(x != y) {
d[x] = y;
add(e[i].u, e[i].v, e[i].w);
add(e[i].v, e[i].u, e[i].w);
}
}
for(int i = 1; i <= n; i++)
if(!vis[i])
f[i][0] = i, w[i][0] = 1e9, dfs(i, 0);
scanf("%d", &q);
for(int x, y, i = 0; i < q; i++) {
scanf("%d%d", &x, &y);
printf("%d\n", lca(x, y));
}
return 0;
}