点分治。
考虑经过点x的路径,对于x,用类似TreeDP的方法,记录no[d],表示路径长度为d时经过边最少的点的编号。
对于已经走过的子树,更新no。对于当前子树,遍历到一个点v,用depth[no[k - dis[v]]] + depth[v]更新答案。
注意给no清零时,用dfs姿势清零,这样做是O(n)的。如果直接用for或者memset,这样做是O(k)的,会TLE。
/* Telekinetic Forest Guard */ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 200005, maxk = 1000005, inf = 0x3f3f3f3f; int n, k, head[maxn], cnt, dis[maxn], depth[maxn], no[maxk], mx[maxn], size[maxn]; int root, nsum, ans; bool vis[maxn]; struct _edge { int v, w, next; } g[maxn << 1]; inline int iread() { int f = 1, x = 0; char ch = getchar(); for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1; for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0'; return f * x; } inline void add(int u, int v, int w) { g[cnt] = (_edge){v, w, head[u]}; head[u] = cnt++; } inline void getroot(int x, int f) { size[x] = 1; mx[x] = 0; for(int i = head[x]; ~i; i = g[i].next) if(!vis[g[i].v] && g[i].v ^ f) { getroot(g[i].v, x); size[x] += size[g[i].v]; mx[x] = max(mx[x], size[g[i].v]); } mx[x] = max(mx[x], nsum - size[x]); if(mx[x] < mx[root]) root = x; } inline void calc(int x, int f) { if(dis[x] > k) return; if(~no[k - dis[x]]) ans = min(ans, depth[no[k - dis[x]]] + depth[x]); for(int i = head[x]; ~i; i = g[i].next) if(!vis[g[i].v] && g[i].v ^ f) { dis[g[i].v] = dis[x] + g[i].w; depth[g[i].v] = depth[x] + 1; calc(g[i].v, x); } } inline void update(int x, int f) { if(dis[x] > k) return; if(!~no[dis[x]] || depth[no[dis[x]]] > depth[x]) no[dis[x]] = x; for(int i = head[x]; ~i; i = g[i].next) if(!vis[g[i].v] && g[i].v ^ f) update(g[i].v, x); } inline void clear(int x, int f) { if(dis[x] > k) return; no[dis[x]] = -1; for(int i = head[x]; ~i; i = g[i].next) if(!vis[g[i].v] && g[i].v ^ f) clear(g[i].v, x); } inline void work(int x) { vis[x] = 1; no[0] = x; dis[x] = depth[x] = 0; for(int i = head[x]; ~i; i = g[i].next) if(!vis[g[i].v]) { dis[g[i].v] = g[i].w; depth[g[i].v] = 1; calc(g[i].v, x); update(g[i].v, x); } clear(x, 0); for(int i = head[x]; ~i; i = g[i].next) if(!vis[g[i].v]) { root = 0; nsum = size[g[i].v]; getroot(g[i].v, 0); work(root); } } int main() { n = iread(); k = iread(); for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0; for(int i = 1; i < n; i++) { int u = iread(), v = iread(), w = iread(); u++; v++; add(u, v, w); add(v, u, w); } for(int i = 0; i <= k; i++) no[i] = -1; mx[0] = ans = inf; root = 0; nsum = n; getroot(1, 0); work(root); if(ans == inf) ans = -1; printf("%d\n", ans); return 0; }
时间: 2024-11-05 10:20:23