LuoguP4211 [LNOI2014]LCA 题解
作者:互联网
P4211 LNOI2014 LCA 题解
快快乐乐的切掉,开开心心的抄题解
总是做不出来这种题
思路一旦清奇,我就懵逼
首先转化,深度其实就是到根节点的节点数
于是我们想把\([l,r]\)这些点到根节点的路径都加一
然后\(z\)直接统计路径和
于是发现不可做,但是可以用\([1,r]\)的减去\([1,l-1]\)的
那么离线询问然后......
code
#include<bits/stdc++.h>
using namespace std;
#define fo(i,x,y) for(int i=(x);i<=(y);i++)
#define fu(i,x,y) for(int i=(x);i>=(y);i--)
int read(){
int s=0,t=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')t=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){s=(s<<3)+(s<<1)+ch-'0';ch=getchar();}
return s*t;
}
const int mod=201314;
const int N=5e4+5;
int n,m;
int to[N],nxt[N],head[N],rp;
void add_edg(int x,int y){
to[++rp]=y;
nxt[rp]=head[x];
head[x]=rp;
}
int siz[N],son[N],fa[N];
int top[N],dfn[N],idf[N],cnt;
void dfs_fi(int x){
siz[x]=1;son[x]=0;
for(int i=head[x];i;i=nxt[i]){
int y=to[i];
dfs_fi(y);
siz[x]+=siz[y];
if(!son[x]||siz[y]>siz[son[x]])son[x]=y;
}
}
void dfs_se(int x,int f){
top[x]=f;dfn[x]=++cnt;idf[cnt]=x;
if(son[x])dfs_se(son[x],f);
for(int i=head[x];i;i=nxt[i]){
int y=to[i];
if(y==son[x])continue;
dfs_se(y,y);
}
}
struct X{
#define ls x<<1
#define rs x<<1|1
int sum[N*4],tag[N*4];
void pushup(int x){sum[x]=(sum[ls]+sum[rs])%mod;}
void pushdown(int x,int l,int r){
int mid=l+r>>1;
tag[ls]=(tag[ls]+tag[x])%mod;
sum[ls]=(sum[ls]+(mid-l+1)*tag[x]%mod)%mod;
tag[rs]=(tag[rs]+tag[x])%mod;
sum[rs]=(sum[rs]+(r-mid)*tag[x]%mod)%mod;
tag[x]=0;
return ;
}
void ins(int x,int l,int r,int ql,int qr){
if(ql>qr)return ;
if(ql<=l&&r<=qr){
sum[x]=(sum[x]+r-l+1)%mod;
tag[x]=(tag[x]+1)%mod;return ;
}
if(tag[x])pushdown(x,l,r);
int mid=l+r>>1;
if(ql<=mid)ins(ls,l,mid,ql,qr);
if(qr>mid)ins(rs,mid+1,r,ql,qr);
pushup(x);
}
int query(int x,int l,int r,int ql,int qr){
if(ql>qr)return 0;
if(ql<=l&&r<=qr)return sum[x];
if(tag[x])pushdown(x,l,r);
int mid=l+r>>1,ret=0;
if(ql<=mid)ret=(ret+query(ls,l,mid,ql,qr))%mod;
if(qr>mid)ret=(ret+query(rs,mid+1,r,ql,qr))%mod;
pushup(x);return ret;
}
#undef ls
#undef rs
}xds;
void change(int x){
while(top[x]!=1){
xds.ins(1,1,n,dfn[top[x]],dfn[x]);
x=fa[top[x]];
}
xds.ins(1,1,n,dfn[1],dfn[x]);
}
int query(int x){
int ret=0;
while(top[x]!=1){
ret=(ret+xds.query(1,1,n,dfn[top[x]],dfn[x]))%mod;
x=fa[top[x]];
}
ret=(ret+xds.query(1,1,n,dfn[1],dfn[x]))%mod;
return ret;
}
struct Q{int l,r,z,ans[2];}q[N];
vector<pair<int,int>> vec[N];
signed main(){
n=read();m=read();
fo(i,2,n)fa[i]=read()+1,add_edg(fa[i],i);
dfs_fi(1);dfs_se(1,1);
fo(i,1,m){
q[i].l=read()+1;q[i].r=read()+1;q[i].z=read()+1;
if(q[i].l-1)vec[q[i].l-1].push_back(make_pair(i,0));
vec[q[i].r].push_back(make_pair(i,1));
}
fo(i,1,n){
// cout<<i<<" ";
change(i);
// cout<<"finish change"<<" ";
for(pair<int,int> i:vec[i])q[i.first].ans[i.second]=query(q[i.first].z);
// cout<<"finish query"<<endl;
}
fo(i,1,m)printf("%d\n",(q[i].ans[1]-q[i].ans[0]%mod+mod)%mod);
}
标签:int,题解,LNOI2014,tag,ret,dfn,LuoguP4211,ql,mod 来源: https://www.cnblogs.com/hzoi-fengwu/p/15699542.html