求问有些什么注意事项
代码如下
// Problem: CF1746D Paths on the Tree
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF1746D
// Memory Limit: 250 MB
// Time Limit: 3000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// Author:zymooll
#include<bits/stdc++.h>
//#define getchar getchar_unlocked
//#define putchar putchar_unlocked
#define int long long
using namespace std;
int read(){
int s=0,w=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-')w=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
s=s*10+c-'0';
c=getchar();
}
return s*w;
}
void print(int x){
if(x<0){
putchar('-');
x=-x;
}
if(x>=10)print(x/10);
putchar(x%10+'0');
return;
}
int t;
int n,k;
int s[200010];
int fa[200010];
int son[200010];
struct Edge{
int v,next;
}edge[400010];
int cut,head[200010];
void add_edge(int u,int v){
edge[++cut].v=v;
edge[cut].next=head[u];
head[u]=cut;
}
int dfs(int node,int nedge){
//cerr<<node<<" "<<nedge<<"\n";
int ans=nedge*s[node];
if(!son[node]){
//cerr<<ans<<"\n";
return ans;
}
int give=nedge/son[node];
int remain=nedge-give*son[node];
vector<int>value;
for(int i=head[node];i;i=edge[i].next){
int v=edge[i].v;
if(v==fa[node]){
continue;
}
int ls=dfs(v,give);
ans+=ls;
value.push_back(ls);
}
priority_queue<int>q;
if(remain){
for(int i=head[node],j=0;i;i=edge[i].next,j++){
int v=edge[i].v;
int more=dfs(v,give+1)-value[j];
q.push(more);
}
for(int i=1;i<=remain;i++){
ans+=q.top();
}
}
//cerr<<ans<<"\n";
return ans;
}
signed main(){
t=read();
while(t--){
//cerr<<"<\n";
//memset(c,0,sizeof(c));
memset(fa,0,sizeof(fa));
memset(son,0,sizeof(son));
memset(head,0,sizeof(head));
cut=0;
n=read(),k=read();
fa[1]=1;
for(int i=2;i<=n;i++){
fa[i]=read();
son[fa[i]]++;
add_edge(i,fa[i]);
add_edge(fa[i],i);
}
for(int i=1;i<=n;i++){
s[i]=read();
}
print(dfs(1,k)),putchar('\n');
}
return 0;
}