题目大意
解题思路
考虑到不能选的点在dfs序上是连续的,可以按价值dp从前和从后做两次,查询时合并即可。
对于卡空间,对询问离线,前缀可以省掉一维。对于卡时间,可以按照当前最大价值作为边界。
code
.pon];
}
int main(){
//freopen("plan.in","r",stdin);
//freopen("plan.out","w",stdout);
freopen("d.in","r",stdin);
freopen("d.out","w",stdout);
scanf("%d",&n);int u,v;
fo(i,1,n-1){
scanf("%d%d",&u,&v);
insert(u,v);insert(v,u);
}
int mx=0;
fo(i,1,n)scanf("%d%d",&w[i],&c[i]),mx+=w[i];
dfs(1,0);
fo(i,1,n)mx2[i]=mx2[i-1]+w[re[i]];
fd(i,n,0)mx3[i]=mx3[i+1]+w[re[i]];
fo(i,0,n+1)fo(j,1,mx+2)g[i][j]=inf;
fd(i,n,1){
int tmp=mx3[i];
fd(j,tmp,w[re[i]])
g[i][j]=min(g[i][j],g[i+1][j-w[re[i]]]+c[re[i]]);
fd(j,tmp,1){
g[i][j]=min(g[i][j],g[i+1][j]);
g[i][j]=min(g[i][j],g[i][j+1]);
}
}
fo(j,1,mx+2)f[j]=inf;
scanf("%d",&q);
fo(i,1,q)scanf("%d%lld",&a[i].pon,&a[i].cost),a[i].pos=i;
sort(a+1,a+q+1,cmp);a[0].pon=1;
fo(i,1,q){
int pre=a[i-1].pon,now=a[i].pon,l=dfn[now]-1,r=low[now]+1,mxx;LL tmp,tmp2,tmp3,tmp4;
fo(j,dfn[pre],l){
tmp=re[j];tmp2=w[tmp];mxx=mx2[j];
fd(k,mxx,tmp2){
tmp3=f[k];tmp4=f[k-tmp2]+c[tmp];
f[k]=min(tmp3,tmp4);
}
fd(j,mxx,1){
tmp3=f[j];tmp4=f[j+1];
f[j]=min(tmp3,tmp4);
}
}
int k=mx3[r];tmp=a[i].pos,tmp2=0;tmp3=a[i].cost;
fo(j,0,mxx){
while(k&&(f[j]+g[r][k]>tmp3))k--;
tmp4=(f[j]+g[r][k]<=tmp3)?(j+k):0;
tmp2=max(tmp2,tmp4);
}
ans[tmp]=tmp2;
}
fo(i,1,q)printf("%lld\n",ans[i]);
return 0;
}