0%

Global Round 23 D 题解

Global Round 23 D 题解

思路

观察到,如果确定了一个点经过的次数,那它的儿子的次数基本确定了,且只受这个点的控制。

所以这道题大概是个子树类 dp。

具体来说,假设一个点经过了 $num$ 次,它有 $k$ 个儿子,考虑儿子走的次数。

由于任意两个儿子之间的次数差不超过 $1$,所以所有儿子必然至少走过 $\lfloor \frac{num}{k}\rfloor$ 次,还要选择 $num\mod k$ 个儿子再走一次。

题目要求答案最大,所以可以直接贪心,选择儿子中贡献最大的 $num\mod k$ 个。

可以考虑每次对每个儿子 $dfs$ 两遍,分别代表走 $\lfloor \frac{num}{k}\rfloor$ 和 $\lfloor \frac{num}{k}\rfloor+1$ 次,选择两者差值最大的 $num\mod k$ 个。

这里一定要以你要走的次数去 $dfs$,而不能仅仅依靠 $dfs(v,1)$ 来判断谁更优,因为次数不同,方案可能截然不同。

而且,也不能选择走 $\lfloor \frac{num}{k}\rfloor+1$ 次中最大的几个,因为在加上它的贡献的同时,还要减去走 $\lfloor \frac{num}{k}\rfloor$ 次的贡献。

由于是树形 dp,所以复杂度是经典的 $O(n\log n)$。

但是,这样写会有大常数,因为每次要 $dfs$ 两遍。建议还是对每一次求出的值记忆化一下,容易证明这样做只会有 $n$ 个状态,所以就是严格的 $O(n\log n)$ 了。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;
const int N = 2e5+10;
int t,n,k,head[N],tot,s[N],cnt[N];
ll f[N],tmp[N];
map<pair<int,int>,ll> mp;
struct e{
int next,to;
} edge[N*2];
void add(int x,int y){
edge[++tot].to = y;
edge[tot].next = head[x];
head[x] = tot;
}
ll dfs(int u,int num){
if (mp.count(make_pair(u,num))) return mp[make_pair(u,num)];
int v,bas = 0,lim = 0;
f[u] = 1ll*num*s[u];
if (cnt[u]) bas = num/cnt[u],lim = num%cnt[u];
ll tmp1,tmp2;
vector<ll> tmp;
vector<ll>().swap(tmp);
for (int i=head[u];i;i = edge[i].next){
v = edge[i].to;
tmp1 = dfs(v,bas);
if (lim) tmp2 = dfs(v,bas+1);
f[u]+=tmp1;
if (lim) tmp.pb(tmp2-tmp1);
}
if (lim){
sort(tmp.begin(),tmp.end(),greater<int>());
for (int i=0;i<lim;i++) f[u]+=tmp[i];
}
mp[make_pair(u,num)] = f[u];
return f[u];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>t;
while (t--){
cin>>n>>k;
memset(head,0,sizeof(int)*(n+10));
memset(cnt,0,sizeof(int)*(n+10));
mp.clear();
tot = 0;
int x;
for (int i=2;i<=n;i++){
cin>>x;
add(x,i),cnt[x]++;
}
for (int i=1;i<=n;i++) cin>>s[i];
cout<<dfs(1,k)<<"\n";
}
return 0;
}