[BZOJ4771][主席树][平衡树]七彩树
作者:互联网
考虑没有距离限制怎么做
一个点的贡献是1,如果它和它在dfs序上相邻的同颜色的点组合,会使它们lca的贡献-1
那就可以用线段树维护了
然后如果有距离限制,可以看做是按深度逐个加点的过程,那就把线段树改成主席树就完了
还要用一个平衡树或者set维护加点的dfs序
Code:
#include<bits/stdc++.h>
#define ll long long
#define db double
#define pb push_back
using namespace std;
inline int read(){
int res=0,f=1;char ch=getchar();
while(!isdigit(ch)) {if(ch=='-') f=-f;ch=getchar();}
while(isdigit(ch)) {res=(res<<1)+(res<<3)+(ch^48);ch=getchar();}
return res*f;
}
const int N=1e5+5;
namespace tree{
int vis[N<<1],head[N<<1],nxt[N<<1],tot=0;
inline void add(int x,int y){vis[++tot]=y;nxt[tot]=head[x];head[x]=tot;}
int fa[N],dep[N],siz[N],hson[N];
void dfs1(int v){
siz[v]=1;
for(int i=head[v];i;i=nxt[i]){
int y=vis[i];
if(y==fa[v]) continue;
fa[y]=v;dep[y]=dep[v]+1;
dfs1(y);
siz[v]+=siz[y];
if(siz[y]>siz[hson[v]]) hson[v]=y;
}
}
int dfn[N],sign=0,id[N],top[N];
void dfs2(int v){
dfn[v]=++sign;id[sign]=v;
top[v]=v==hson[fa[v]]?top[fa[v]]:v;
for(int i=head[v];i;i=nxt[i])
if(!top[vis[i]]) dfs2(vis[i]);
}
inline int lca(int x,int y){
while(top[x]!=top[y])
dep[top[x]]>dep[top[y]]?x=fa[top[x]]:y=fa[top[y]];
return dep[x]<dep[y]?x:y;
}
}
using namespace tree;
namespace President_tree{
struct seg{int ls,rs,siz;}tr[N*50];int cnt=0;
#define lc(k) tr[k].ls
#define rc(k) tr[k].rs
void ins(int &k1,int k2,int l,int r,int pos,int val){
tr[k1=++cnt]=tr[k2];tr[k1].siz+=val;
if(l==r) return;
int mid=l+r>>1;
if(pos<=mid) ins(lc(k1),lc(k2),l,mid,pos,val);
else ins(rc(k1),rc(k2),mid+1,r,pos,val);
}
int query(int k,int l,int r,int ql,int qr){
if(!k) return 0;
if(ql<=l && r<=qr) return tr[k].siz;
int mid=l+r>>1;
if(qr<=mid) return query(lc(k),l,mid,ql,qr);
else if(ql>mid) return query(rc(k),mid+1,r,ql,qr);
else return query(lc(k),l,mid,ql,qr)+query(rc(k),mid+1,r,ql,qr);
}
}
using namespace President_tree;
inline bool cmp(int a,int b){return dep[a]<dep[b];}
set<int>s[N];
set<int>::iterator it;
int ans=0;
int v[N],num[N],rt[N];
int main(){
int t=read();
while(t--){
memset(head,0,sizeof(head));
memset(fa,0,sizeof(fa));
memset(rt,0,sizeof(rt));
memset(top,0,sizeof(top));
cnt=tot=sign=ans=0;
int n=read(),m=read();
for(int i=1;i<=n;i++){v[i]=read();num[i]=i;s[i].clear();}
for(int i=2;i<=n;i++){fa[i]=read();add(fa[i],i);}
dep[1]=1;dfs1(1);dfs2(1);
sort(num+1,num+n+1,cmp);
for(int i=1;i<=n;i++){
int j=num[i],a=0,b=0;
it=s[v[j]].lower_bound(dfn[j]);
ins(rt[dep[j]],rt[dep[num[i-1]]],1,n,dfn[j],1);
if(it!=s[v[j]].end()) b=id[*it],ins(rt[dep[j]],rt[dep[j]],1,n,dfn[lca(b,j)],-1);
if(it!=s[v[j]].begin()) --it,a=id[*it],ins(rt[dep[j]],rt[dep[j]],1,n,dfn[lca(a,j)],-1);
if(a && b) ins(rt[dep[j]],rt[dep[j]],1,n,dfn[lca(a,b)],1);
s[v[j]].insert(dfn[j]);
}
for(int i=1;i<=m;i++){
int x=read()^ans,y=read()^ans;
ans=query(rt[min(dep[x]+y,dep[num[n]])],1,n,dfn[x],dfn[x]+siz[x]-1);
cout<<ans<<"\n";
}
}
return 0;
}
标签:七彩,ch,BZOJ4771,int,top,memset,fa,read,平衡 来源: https://blog.csdn.net/qq_43346903/article/details/100114341