为什么把 dfs2 的 for(int i=0;i<=k;i++) 改成 for(int i=1;i<=k;i++) 只有30分,dp[u][0]已经在 dfs2 前面初始化了。
#include <bits/stdc++.h>
using namespace std;
#define sp putchar(' ')
#define en putchar('\n')
#define pb push_back
#define int long long
#define P 998244353
#define HP 1000000000000002097
#define N (int)(1e5+5)
int read(){ char ch=getchar();int x=0,f=1;while(ch>'9' || ch<'0'){if(ch=='-') f=-1;ch=getchar();}while(ch>='0' && ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();return x*f; }
void print(int x){ if(x<0) putchar('-'),x=-x;if(x>9)print(x/10);putchar(x%10+'0'); }
int n,k;
vector<int> e[N];
int c[N],f[N][25],dp[N][25];
void dfs(int u,int fa)
{
for(int i=0;i<=k;i++) f[u][i]=c[u];
for(auto v:e[u]){
if(v==fa) continue;
dfs(v,u);
for(int i=1;i<=k;i++){
f[u][i]+=f[v][i-1];
}
}
}
void dfs2(int u,int fa)
{
for(int i=0;i<=k;i++){
dp[u][i]=f[u][i]+dp[fa][i-1]-f[u][i-2];
}
for(auto v:e[u]){
if(v==fa) continue;
dfs2(v,u);
}
}
signed main()
{
ios::sync_with_stdio(0);cin.tie(0),cout.tie(0);
cin>>n>>k;
for(int i=1,u,v;i<n;i++){
cin>>u>>v;
e[u].pb(v);e[v].pb(u);
}
for(int i=1;i<=n;i++) cin>>c[i];
dfs(1,0);
for(int i=0;i<=k;i++) dp[0][i]=f[1][i-1],dp[i][0]=c[i];
dfs2(1,0);
for(int i=1;i<=n;i++) cout<<dp[i][k]<<"\n";
return 0;
}