题解:CF1987E Wonderful Tree!
来个不用动脑子的做法。
分析
直接的想法就是 dp。
令
代码
#include<bits/stdc++.h>
#define MAXN 5005
#define int long long
using namespace std;
int n;
int a[MAXN];
vector<int>G[MAXN];
struct P{
int x,y;
};
P add(P p1,P p2){
return P{p1.x+p2.x,p1.y+p2.y};
}
P del(P p1,P p2){
return P{p1.x-p2.x,p1.y-p2.y};
}
vector<P>f[MAXN];
vector<P> unite(vector<P> f1,vector<P> f2){
if(f1.empty())return f2;
if(f2.empty())return f1;
vector<P>v;
v.push_back(add(f1[0],f2[0]));
int l1=1,l2=1;
P lst=v[0];
while(l1<f1.size()&&l2<f2.size()){
if((f1[l1].y-f1[l1-1].y)/(f1[l1].x-f1[l1-1].x)<=(f2[l2].y-f2[l2-1].y)/(f2[l2].x-f2[l2-1].x))
v.push_back(add(del(f1[l1],f1[l1-1]),lst)),l1++;
else v.push_back(add(del(f2[l2],f2[l2-1]),lst)),l2++;
lst=v.back();
}
while(l1<f1.size()){
v.push_back(add(del(f1[l1],f1[l1-1]),lst));l1++;
lst=v.back();
}
while(l2<f2.size()){
v.push_back(add(del(f2[l2],f2[l2-1]),lst));l2++;
lst=v.back();
}
return v;
}
void dfs(int x,int pre){
f[x].clear();
for(auto y:G[x]){
if(y==pre)continue;
dfs(y,x);
vector<P>v;
f[x]=unite(f[x],f[y]);
swap(f[y],v);
}
if(f[x].size()){
if(f[x][0].x<=a[x]){
vector<P>v;
int t=0;
while(f[x][t].x<=a[x]&&t<f[x].size())t++;
P p1=f[x][t-1],p2=f[x][t];
v.push_back(P{a[x],(a[x]-p1.x)*(p2.y-p1.y)/(p2.x-p1.x)+p1.y});
for(int i=t;f[x].size()>i;i++)v.push_back(f[x][i]);
f[x]=v;
}else{
P p=*f[x].begin();
f[x].insert(f[x].begin(),P{a[x],p.y});
}
for(int i=1;f[x].size()>i;i++)f[x][i].y+=f[x][i].x-a[x];
}else{
f[x].push_back(P{a[x],0});
f[x].push_back(P{(int)1e9+a[x],(int)1e9});
}
}
void work(){
cin>>n;
for(int i=1;n>=i;i++)cin>>a[i];
for(int i=1;n>=i;i++)G[i].clear();
int x,y;
for(int i=2;n>=i;i++){
cin>>x;
G[i].push_back(x);
G[x].push_back(i);
}
dfs(1,0);
cout<<f[1][0].y<<endl;
}
signed main(){
int _T;
cin>>_T;
while(_T--)work();
return 0;
}