[Luogu] 运输计划
https://www.luogu.org/problemnew/show/2680
inline 神奇的东西
最好戒掉吧(read()除外)
这道题将求解性问题转化为判定性问题,当然就是二分答案了
二分删掉边后最短路径的最大值 mid
将所有的比mid大的询问求交集:树上差分,cnt[s] ++, cnt[t] ++, cnt[lca(s, t)] -= 2
最后统计每个节点以及该节点的子树的cnt的和,若
和==比mid大的询问数量,则说明该点与其父亲组成
的这条边在所有边的交集上
判断 :最大路径-最大的交集中的边
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; #define gc getchar() int Cnt[N], tree[N], fa[N], siz[N], son[N], topp[N], deep[N], head[N]; int n, m, now = 1, tim; int L[N], R[N], D[N], dis[N]; int LCA[N]; struct Node {int u, v, w, nxt;} G[N << 1]; int js; inline int read(){ int x = 0; char c = gc; while(c < '0' || c > '9') c = gc; while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = gc; return x; } void add(int u, int v, int w){ G[now].u = u; G[now].v = v; G[now].w = w; G[now].nxt = head[u]; head[u] = now ++; } void dfs_find_son(int u, int f_, int dep){ fa[u] = f_; deep[u] = dep; siz[u] = 1; for(int i = head[u]; ~ i; i = G[i].nxt){ int v = G[i].v; if(v != f_){ dis[v] = dis[u] + G[i].w; dfs_find_son(v, u, dep + 1); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } } } void dfs_to_un(int u, int tp){ topp[u] = tp; tree[u] = ++ tim; if(!son[u]) return ; dfs_to_un(son[u], tp); for(int i = head[u]; ~ i; i = G[i].nxt){ int v = G[i].v; if(v != son[u] && v != fa[u]) dfs_to_un(v, v); } } int Lca(int x, int y){ int tp1 = topp[x], tp2 = topp[y]; while(tp1 != tp2){ if(deep[tp1] < deep[tp2]) swap(x, y), swap(tp1, tp2); x = fa[tp1]; tp1 = topp[x]; } return deep[x] > deep[y] ? y : x; } void Calc(int u){ if(!son[u]) return ; for(int i = head[u]; ~ i; i = G[i].nxt){ int v = G[i].v; if(v != fa[u]){ Calc(v); Cnt[u] += Cnt[v]; } } } bool See(int x){ for(int i = 1; i <= n; i ++) Cnt[i] = 0; int B(0); int Max_dis = -1, Max_w = -1; for(int i = 1; i <= m; i ++) if(D[i] > x) Max_dis = max(Max_dis, D[i]), B ++, Cnt[L[i]] ++, Cnt[R[i]] ++, Cnt[LCA[i]] -= 2; Calc(1); for(int i = 1; i <= n; i ++) if(Cnt[i] == B) Max_w = max(Max_w, dis[i] - dis[fa[i]]); return Max_dis - Max_w <= x ? 1 : 0; } int main() { n = read(); m = read(); int l = 0, r = 0, ans; for(int i = 1; i <= n; i ++) head[i] = -1; for(int i = 1; i < n; i ++){ int u = read(), v = read(), w = read(); add(u, v, w); add(v, u, w); } dfs_find_son(1, 0, 1); dfs_to_un(1, 1); for(int i = 1; i <= m; i ++){ L[i] = read(); R[i] = read(); LCA[i] = Lca(L[i], R[i]); D[i] = dis[L[i]] + dis[R[i]] - (dis[LCA[i]] * 2); r = max(r, D[i]); } while(l <= r){ int mid = (l + r) >> 1; if(See(mid)) ans = mid, r = mid - 1; else l = mid + 1; } printf("%d", ans); return 0; } /* 6 3 1 2 3 1 6 4 3 1 7 4 3 6 3 5 5 3 6 2 5 4 5 */