传送门
这里由于最高的量ma过大(这里可以用离散化削减空间)
1:切忌不可以使用空树,否则必超时
2:再者这里的数组空间不再像以前的32倍,而是40倍,
3:update更新函数使用时,不可以返回int,会超时,使用引用就不超时了(好坑呀)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MX=2e5+9;
struct node{
int to;
int next;
ll val;
}edge[MX<<1];
int tot=0,head[MX];
void add(int u,int to,ll val){
edge[tot].next=head[u];
edge[tot].to=to;
edge[tot].val=val;
head[u]=tot++;
}
int n,lc[MX<<5],rc[MX<<5],to,sz=0,st[MX],ed[MX],tr[MX];
ll sum[MX<<5],cnt[MX<<5],dis[MX],val,ma=0;
//void build(int &o,ll l,ll r){
// o=++sz;
// cnt[o]=sum[o]=0;
// if( l==r )
// return ;
// ll mid=(l+r)>>1;
// build(lc[o],l,mid);
// build(rc[o],mid+1,r);
//}
void update(int &oo,int o,ll l,ll r,ll k){ // 这里必须要用引用,如果是返回oo,会超时
oo=++sz;
sum[oo]=sum[o]+k,cnt[oo]=cnt[o]+1;
lc[oo]=lc[o],rc[oo]=rc[o];
if( l==r )
return ;
ll mid=(l+r)>>1;
if( k<=mid )
update(lc[oo],lc[oo],l,mid,k);
else
update(rc[oo],rc[oo],mid+1,r,k);
return ;
}
void dfs(int u,int f,ll last){
st[u]=++tot;
dis[u]=last;
update(tr[tot],tr[tot-1],1,ma,last); // 每一颗树存它所有子树到根节点的距离
for( int i=head[u] ; ~i ; i=edge[i].next ){
int v=edge[i].to;
if( v==f )
continue;
dfs(v,u,last+edge[i].val);
}
ed[u]=tot;
}
ll anssum,anscnt;
void que(int u,int v,ll l,ll r,ll L,ll R){
if( L<=l && r<=R ){
anssum+=(sum[v]-sum[u]);
anscnt+=(cnt[v]-cnt[u]);
return ;
}
ll mid=(l+r)>>1;
if( L<=mid )
que(lc[u],lc[v],l,mid,L,R);
if( mid<R )
que(rc[u],rc[v],mid+1,r,L,R);
}
int main()
{
freopen("input.txt","r",stdin);
memset(head,-1,sizeof(head));
scanf("%d",&n);
for( int i=1 ; i<=n-1 ; i++ ){
scanf("%d %lld",&to,&val);
add(to,i+1,val),add(i+1,to,val);
ma+=val;
}
// printf("%lld\n",ma);
tot=0;
// build(tr[0],1,ma); // 由于ma过于大,若建一颗空树,则耗费大量的时间
dfs(1,0,0);
int q;
scanf("%d",&q);
while( q-- ){
int x;ll k;
scanf("%d %lld",&x,&k);
anssum=anscnt=0;
k+=dis[x];
que(tr[st[x]],tr[ed[x]],1,ma,k,ma);
// printf("%lld %lld %lld\n",anssum,anscnt,k);
printf("%lld\n",anssum-anscnt*dis[x]);
}
return 0;
}