寻找路径 / Race
题目链接:ybt金牌导航5-2-4 / luogu P4149
题目大意
给你一个树,你要找到一条路径,使得路径上边权和为 k,且路径上边的数量尽可能小。
如果能找到输出路径上边的数量,否则输出 -1。
思路
首先看到这些东西直接上点分治。
但它是规定了路径边权,然后会变的是边数。
看到 k k k 最多只有 1 0 6 10^6 106,我们考虑反过来,数组里面记录边权和为 i i i 的路径最少要走多少条边。
由于是判断是否可能,不能用全部减非法,而是要用按顺序枚举,跟前面匹配的方法。
(记得初始化不要直接枚举桶每个位置,会超时)
代码
#include<cstdio>
#include<cstring>
#include<iostream>
#define INF 1e9
using namespace std;
struct node {
int x, to, nxt;
}e[400001];
int n, k, x, y, z, le[200001], KK;
int root, f[200001], sz[200001];
int sum, disu[1000001], a[200001];
int ans, b[200001], befn;
bool in[200001];
void add(int x, int y, int z) {
e[++KK] = (node){z, y, le[x]}; le[x] = KK;
e[++KK] = (node){z, x, le[y]}; le[y] = KK;
}
void getroot(int now, int father) {
sz[now] = 1;
f[now] = 0;
for (int i = le[now]; i; i = e[i].nxt)
if (!in[e[i].to] && e[i].to != father) {
getroot(e[i].to, now);
sz[now] += sz[e[i].to];
f[now] = max(f[now], sz[e[i].to]);
}
f[now] = max(f[now], sum - sz[now]);
if (f[now] < f[root]) root = now;
}
void get_road(int now, int father, int deg, int dist) {
if (dist > k) return ;
a[++a[0]] = dist;
b[a[0]] = deg;
for (int i = le[now]; i; i = e[i].nxt)
if (!in[e[i].to] && e[i].to != father) {
get_road(e[i].to, now, deg + 1, dist + e[i].x);
}
}
void work(int now) {
a[0] = 0;
disu[0] = 0;
for (int i = le[now]; i; i = e[i].nxt)
if (!in[e[i].to]) {
befn = a[0];
get_road(e[i].to, now, 1, e[i].x);
for (int j = befn + 1; j <= a[0]; j++)
ans = min(ans, b[j] + disu[k - a[j]]);
for (int j = befn + 1; j <= a[0]; j++) {
disu[a[j]] = min(disu[a[j]], b[j]);
}
}
for (int i = 1; i <= a[0]; i++)
disu[a[i]] = INF;
}
void slove(int now) {
in[now] = 1;
work(now);
for (int i = le[now]; i; i = e[i].nxt)
if (!in[e[i].to]) {
root = 0;
sum = sz[e[i].to];
getroot(e[i].to, now);
slove(root);
}
}
int main() {
for (int i = 1; i <= 1000000; i++)
disu[i] = INF;
ans = INF;
scanf("%d %d", &n, &k);
for (int i = 1; i < n; i++) {
scanf("%d %d %d", &x, &y, &z);
x++;
y++;
add(x, y, z);
}
sum = n;
f[0] = INF;
getroot(1, 0);
slove(root);
if (ans >= n) printf("-1");
else printf("%d", ans);
return 0;
}