这题需要用到,dfs序时间戳,可持久化字典树
dfs时间戳就是把一棵树转化成线性结构,每棵子树就是线上的一个区间,可以用ll,rr数组保存起来
接下来就是在这个线性结构上构造可持续化字典树,之前没有学过的很难看懂这部分代码
按这道题来说,我的理解就是:
可持久化字典树可以把本来需要2^31*N的树,压缩为31*N的空间,并实现
快速的区间查询
每个数字在字典树上都可以看成一条路径,由010101010......构成的路径
首先要动态分配字典树的节点,在线性结构上按照给出的N个数字建N个字典树
第0个树初始化为空树,cnt=0,指针都指向0,接下来建的第一个树先初始化为前一个树,就是0
再按照第一个树的数字建立字典树,在走过的路径上cnt+1,并且分配了节点
如果没有走过的怎么办?因为继承了前一个树的数据,所以没有走过的指针就指向前一个树指向的地方
前面怎么样不用管,可以知道这个指针会指向上一个路径相等的数,或者指向0
这样一直向下,就可以建成一个31*N的大字典树,每个树的路径上的cnt都是前面所有数路径的和
查询的时候,先按照ll,rr找到子树所在的区间,从左右两端入手,用贪心的方法找最大值
后面的cnt>前面的cnt就说明有这个路径的数字在区间内,然后按指针向下寻找
最后加起来返回
可持久化字典树说起来真的很复杂,有耐心的话可以看代码模拟慢慢理解
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=1e5+10;
const int B=29;
struct edge
{
int to,next;
}e[N];
int head[N],tot;
void addedge(int u,int v)
{
e[tot].to=v;
e[tot].next=head[u];
head[u]=tot++;
}
struct Tire //字典树
{
int next[2];
int cnt;
}t[31*N];
int idx,cur; //树节点个数,字典树节点个数
int ll[N],rr[N],root[N]; //每个子树区间左右标点,和每个节点的字典树入口
int a[N];
void update(int &S,int E,int n,int d)
{
S=++cur;
t[S]=t[E];
t[S].cnt++;
if(d<0) return;
int temp=(n>>d)&1;
update(t[S].next[temp],t[E].next[temp],n,d-1);
}
void dfs_build(int u)
{
ll[u]=++idx;
update(root[ll[u]],root[ll[u]-1],a[u],B);
for(int i=head[u];~i;i=e[i].next)
dfs_build(e[i].to);
rr[u]=idx;
}
int query(int S,int E,int n,int d)
{
if(d<0) return 0;
int temp=(n>>d)&1;
if(t[t[E].next[temp^1]].cnt-t[t[S].next[temp^1]].cnt>0)
return (1<<d)+query(t[S].next[temp^1],t[E].next[temp^1],n,d-1);
else return query(t[S].next[temp],t[E].next[temp],n,d-1);
}
void init() //初始化
{
idx=cur=tot=0;
memset(head,-1,sizeof(head));
t[0].next[0]=t[0].next[1]=t[0].cnt=0;
}
int main()
{
int n,q,f,u,x;
while(~scanf("%d%d",&n,&q))
{
init();
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=2;i<=n;i++)
{
scanf("%d",&f);
addedge(f,i);
}
dfs_build(1);
while(q--)
{
scanf("%d%d",&u,&x);
int ans=query(root[ll[u]-1],root[rr[u]],x,B);
printf("%d\n",ans);
}
}
return 0;
}