#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=5e5+10;
struct edge{
int to,nxt;
}d[N];int head[N],cnt=1;
void add(int u,int v){ d[++cnt]=(edge){v,head[u]},head[u]=cnt;}
struct node{
int l,r,id;
};vector<node>vec[N],Vec[N];
struct BIT{
int n,c[N];//n为所维护的bit的范围,注意不要混用,离散化时会改变范围
void init(int _n){n=_n;for(int i=1;i<=n;++i) c[i]=0;}
int lowbit(int x){return x&(-x);}//负数为对应正数二进制保留最低位1及之前的0不变,其它取反 故该操作可获得x最位为1对应的值(2的几次方)
int get_sum(int k){int ans=c[k];while((k-=lowbit(k))>0) ans+=c[k];return ans;}
void add(int t,int v){c[t]+=v;while((t+=lowbit(t))<=n) c[t]+=v;}
}bit1;
int n,m,son[N],siz[N],deep[N],ans[N][20],an[N];
int t[N];
void dfs(int u,int father,int depth){
siz[u]=1,deep[u]=depth,ans[u][0]=father;
int maxson=-1;
for(int i=1;i<=18;i++)
ans[u][i]=ans[ ans[u][i-1]][i-1];
for(int i=head[u];i;i=d[i].nxt ){
int v=d[i].to;
if( v==father ) continue;
dfs(v,u,depth+1);
siz[u]+=siz[v];
if( maxson<siz[v] ) maxson=siz[v],son[u]=v;
}
}
int nowson,shu[N];
int k_th(int u,int k){
for(int i=0;i<=18;i++)
if( ((1<<i)&k) ) u=ans[u][i];
return u;
}
void update(int u,int father,int val){
bit1.add(t[u],val);
for(int i=head[u];i;i=d[i].nxt){
int v=d[i].to;
if(v==father||v==nowson) continue;
update(v,u,val);
}
}
void solve(int u,int father){
for(int i=0;i<vec[u].size();i++){
auto v=vec[u][i];
if(t[u]<v.l||t[u]>v.r) continue;
int l=0,r=deep[u]-1;
while(l<r){
int mid=(r+l+1)/2;
if(t[k_th(u,mid)]>=v.l&&t[k_th(u,mid)]<=v.r){
l=mid;
}else r=mid-1;
}
Vec[k_th(u,l)].push_back({v.l,v.r,v.id});
}
for(int i=head[u];i;i=d[i].nxt){
int v=d[i].to;
if(v==father) continue;
solve(v,u);
}
}
void dsu(int u,int father,bool keep){
for(int i=head[u];i;i=d[i].nxt){
int v=d[i].to;
if(v==father||v==son[u]) continue;
dsu(v,u,0);
}
if(son[u]) dsu(son[u],u,1),nowson=son[u];
update(u,father,1);nowson=0;
for(int i=0;i<Vec[u].size();i++){
auto v=Vec[u][i];
int l=v.l,r=v.r;
if(t[u]>=v.l&&t[u]<=v.r&&l>=2) an[v.id]=bit1.get_sum(r)-bit1.get_sum(l-1);
else if(t[u]>=v.l&&t[u]<=v.r&&l==1) an[v.id]=bit1.get_sum(r);
}
if(keep==0) update(u,father,-1);
}
int q,l[N],r[N],x[N];
map<int,int> reto;
vector<int> g;
int32_t main(){
bit1.init(N-1);
scanf("%lld",&n);for(int i=1;i<n;i++){int x,y;scanf("%lld%lld",&x,&y);add(x,y);add(y,x);}
dfs(1,0,1);
for(int i=1;i<=n;i++) scanf("%lld",&t[i]),g.push_back(t[i]);
scanf("%lld",&q);
for(int i=1;i<=q;i++){
scanf("%lld%lld%lld",&x[i],&l[i],&r[i]);
g.push_back(l[i]);g.push_back(r[i]);
}
sort(g.begin(),g.end());
g.erase(unique(g.begin(),g.end()),g.end());
for(int i=0;i<g.size();i++){reto[g[i]]=i+1;}
for(int i=1;i<=n;i++) t[i]=reto[t[i]];
for(int i=1;i<=q;i++){
l[i]=reto[l[i]],r[i]=reto[r[i]];
vec[x[i]].push_back({l[i],r[i],i});
}
solve(1,0);
dsu(1,0,1);
for(int i=1;i<=q;i++){
printf("%lld\n",an[i]);
}
}
2021牛客暑期多校训练营9 Eyjafjalla(dsu+离散+倍增
最新推荐文章于 2022-03-14 18:13:28 发布