传送门
Luogu
解题思路
首先这题可以直接二分答案,然后我们每次都把属于长度大于二分值的路径上的边标记一次,表示选这条边可以优化几条路径。
然后我们显然是要选一条覆盖次数等于需要覆盖的路径数并且长度大于等于最长路径-二分值的路径,不然就无解。
还有一性质要提一下:这条被选的边一定在最长的路径上,显然吧?
细节注意事项
- 咕咕咕。
参考代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <ctime>
#define rg register
using namespace std;
template < typename T > inline void read(T& s) {
s = 0; int f = 0; char c = getchar();
while (!isdigit(c)) f |= (c == '-'), c = getchar();
while (isdigit(c)) s = s * 10 + (c ^ 48), c = getchar();
s = f ? -s : s;
}
const int _ = 300002;
int tot, head[_], nxt[_ << 1], ver[_ << 1], w[_ << 1];
inline void Add_edge(int u, int v, int d)
{ nxt[++tot] = head[u], head[u] = tot, ver[tot] = v, w[tot] = d; }
int n, m, dep[_], dis[_], fa[20][_], tofa[_], F[_];
struct node { int s, t, lca, dis; } p[_];
inline void dfs(int u, int f) {
fa[0][u] = f;
dep[u] = dep[f] + 1;
for (rg int i = 1; i <= 19; ++i)
fa[i][u] = fa[i - 1][fa[i - 1][u]];
for (rg int i = head[u]; i; i = nxt[i]) {
int v = ver[i]; if (v == f) continue;
dis[v] = dis[u] + w[i], dfs(v, u);
}
}
inline int LCA(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
for (rg int i = 19; ~i; --i)
if (dep[fa[i][x]] >= dep[y]) x = fa[i][x];
if (x == y) return x;
for (rg int i = 19; ~i; --i)
if (fa[i][x] != fa[i][y]) x = fa[i][x], y = fa[i][y];
return fa[0][x];
}
int flag, cnt, maxd, maxw;
inline void dfss(int u, int f, int mid) {
if (flag) return ;
for (rg int i = head[u]; i; i = nxt[i]) {
int v = ver[i]; if (v == f) continue;
dfss(v, u, mid), F[u] += F[v];
if (F[v] == cnt && w[i] >= maxd - mid) { flag = 1; return ; }
}
}
inline bool check(int mid) {
memset(F + 1, 0, sizeof (int) * n);
cnt = flag = 0;
for (rg int i = 1; i <= m; ++i)
if (p[i].dis > mid) ++F[p[i].s], ++F[p[i].t], F[p[i].lca] -= 2, ++cnt;
dfss(1, 0, mid);
return flag;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.in", "r", stdin);
freopen("out.out", "w", stdout);
#endif
read(n), read(m);
for (rg int u, v, d, i = 1; i < n; ++i) {
read(u), read(v), read(d);
Add_edge(u, v, d), Add_edge(v, u, d), maxw = max(maxw, d);
}
dfs(1, 0);
for (rg int i = 1; i <= m; ++i) {
read(p[i].s), read(p[i].t);
p[i].lca = LCA(p[i].s, p[i].t);
p[i].dis = dis[p[i].s] + dis[p[i].t] - 2 * dis[p[i].lca];
maxd = max(maxd, p[i].dis);
}
int l = maxd - maxw, r = maxd + 1;
while (l < r) {
int mid = (l + r) >> 1;
if (check(mid)) r = mid;
else l = mid + 1;
}
printf("%d\n", l);
return 0;
}
完结撒花 \(qwq\)