[NOIP2025] 树的价值 / tree(官方数据)的代码 B4300
C++#include<bits/stdc++.h>
#define int long long
using namespace std;
int dp[8009][809];
int f[8009][809];
vector<int> s[8009];
int dep[8009];
int ped[8009];
int sz[8009];
int pd[8009][809];
int fa[8009];
int dfn[8009];//point i's bianhao
int rr[8009];//bianhao's r
int inn;
struct szsz{
int f[8009];
int lowbit(int t){
return t&(-t);
}
void op(int t,int k){
while(t<=8001){
f[t]+=k;
t+=lowbit(t);
}
}
int query(int t){
int ans;
ans=0;
while(t){
ans+=f[t];
t-=lowbit(t);
}
return ans;
}
void pls(int l,int r,int k){
op(l,k),op(r+1,-k);
}
}w[809];
void fs(int t){
int cc;
cc=inn+1;
dfn[t]=++inn;
for(auto v:s[t]){
fs(v);
}
rr[cc]=inn;
}
void zy(int t,int rt){
if(dep[t]-dep[rt]+1>dep[t]){
return;
}
for(auto v:s[t]){
zy(v,rt);
}
dp[rt][dep[t]-dep[rt]+1]=max(dp[rt][dep[t]-dep[rt]+1],w[dep[t]-dep[rt]+1].query(dfn[t])+(dep[t]-dep[rt])*(dep[t]-dep[rt]+1));
}
void dfs(int t){
ped[t]=1;
sz[t]=1;
for(auto v:s[t]){
dfs(v);
ped[t]=max(ped[t],ped[v]+1);
sz[t]+=sz[v];
}for(int ma=1;ma<=dep[t]+1;ma++){
for(auto v:s[t]){
pd[t][ma]+=dp[v][ma];
}
}
for(int ma=1;ma<=dep[t];ma++){
int sum;
sum=0;
for(auto v:s[t])
sum+=dp[v][ma];
for(auto v:s[t])
f[t][ma]=max(f[t][ma],sum-dp[v][ma]+f[v][ma+1]);
f[t][ma]+=ma;
w[ma].pls(dfn[t],dfn[t],f[t][ma]);
}
dp[t][1]=f[t][1];
for(int i=1;i<=dep[t]+1;i++){
int cc=0;
for(auto v:s[t]){
cc+=dp[v][i];
}
for(auto v:s[t]){
cc-=dp[v][i];
w[i].pls(dfn[v],rr[dfn[v]],cc);
cc+=dp[v][i];
}
}
zy(t,t);
for(int ma=ped[t];ma<=dep[t];ma++){
dp[t][ma]=sz[t]*ma;
}
}
void _main(){
int n,m;
cin>>n>>m;
inn=0;
for(int i=1;i<=n;i++){
s[i].clear();
}
memset(dp,0,sizeof(dp));
memset(pd,0,sizeof(pd));
memset(f,0,sizeof(f));
memset(w,0,sizeof(w));
dep[1]=1;
for(int i=2;i<=n;i++){
int faa;
cin>>faa;
dep[i]=dep[faa]+1;
fa[i]=faa;
s[faa].push_back(i);
}
fs(1);
dfs(1);
cout<<dp[1][1]<<endl;
}
signed main(){
//freopen("tree.in","r",stdin);
//freopen("tree.out","w",stdout);
std::ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
_main();
}
return 0;
}
代码2025年
9月:中平:17,22 2(天)
凶:27,30 2(天)
大凶:14,16 2(天)
小吉:21,24 2(天)
中吉:20,23,25,26,28,29 6(天)
大吉:15,18,19 3(天)
2025年
10月:大凶:1,26,29 3(天)
小吉:8,9,17,25 4(天)
中吉:10,13,16,20,22,23,24,28,31 9(天)!!!!!!
中平:12,14,15,18,30 5(天)
凶:19,21,27 3(天)
2025年
11月:中平:7,9,14,30 4(天)
凶:10,13,16,20,28 4(天)
大凶:22,23,26 3(天)
小吉:4 1(天)
中吉:3,6,8,11,12,17,18,19,25,27,29 8(天)!!!!!!!
大吉:1,2,5,15,24 5(天)
2025年
12月:中平:1,3,4,8,10,23,24 7(天)
凶:2,9,17,20,25 5(天)
大凶:5,6 2(天)
小吉:14,15,16,18,22 5(天)
中吉:7,12,13,21 3(天)
大吉:11,19 2(天)