P4211 [LNOI2014] LCA题解
感觉是一个很好的树剖题。
大致思路
一般遇到这种题,我们首先考虑离线。我们按照询问的右端点排序,排完序后我们就要用我们的经典操作了:
我们遇到左端点后,加入贡献;遇到右端点后,记录答案,撤销贡献。\
当然,在这道题目里可能会略微不同。我们首先弱化一下这个问题:如果问的是
复杂度
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=1e5+5,MOD=201314;
vector<int> G[N];
ll n,m,dfn[N],tp[N],f[N],dep[N],sz[N];
ll hson[N],TIME,ans[N];
void dfs1(ll x,ll fa){
dep[x]=dep[fa]+1,sz[x]=1;
for(ll v:G[x]){
if(dep[v]) continue;
dfs1(v,x);
sz[x]+=sz[v];
if(hson[x]==-1||sz[hson[x]]<sz[v])
hson[x]=v;
}
}
void dfs2(ll x,ll t){
dfn[x]=++TIME,tp[x]=t;
if(hson[x]==-1) return ;
dfs2(hson[x],t);
for(int v:G[x]){
if(v==hson[x]||v==f[x]) continue;
dfs2(v,v);
}
}
struct QUERY{
ll x,id,flag,z;
}q[N];
ll cnt=0;
ll cal(ll x){
return (x%MOD+MOD)%MOD;
}
bool cmp(QUERY x,QUERY y){
return x.x<y.x;
}
template<typename TT>
class SGT{
ll T[N<<2],tag[N<<2];
void pushdown(ll x,ll l,ll r){
if(!tag[x]) return ;
ll mid=(l+r)>>1;
tag[x<<1]=cal(tag[x<<1]+tag[x]);
tag[x<<1|1]=cal(tag[x<<1|1]+tag[x]);
T[x<<1]=cal(T[x<<1]+tag[x]*(mid-l+1)%MOD);
T[x<<1|1]=cal(T[x<<1|1]+tag[x]*(r-mid)%MOD)%MOD;
tag[x]=0;
}
void push_up(ll x){
T[x]=cal(T[x<<1]+T[x<<1|1]);
}
public:
void upd(ll x,ll l,ll r,ll ql,ll qr,ll k){
if(ql<=l&&r<=qr){
T[x]=cal(T[x]+r-l+1);
tag[x]=cal(tag[x]+1);
return ;
}
ll mid=(l+r)>>1;
pushdown(x,l,r);
if(ql<=mid) upd(x<<1,l,mid,ql,qr,k);
if(qr>mid) upd(x<<1|1,mid+1,r,ql,qr,k);
push_up(x);
}
ll query(ll x,ll l,ll r,ll ql,ll qr){
if(ql<=l&&r<=qr) return T[x];
ll mid=(l+r)>>1;
pushdown(x,l,r);
ll res=0;
if(ql<=mid) res=cal(res+query(x<<1,l,mid,ql,qr));
if(qr>mid) res=cal(res+query(x<<1|1,mid+1,r,ql,qr));
return res;
}
};
SGT<int> T;
void upd_P(ll x,ll y){
while(tp[x]!=tp[y]){
if(dep[tp[x]]<dep[tp[y]]) swap(x,y);
T.upd(1,1,n,dfn[tp[x]],dfn[x],1);
x=f[tp[x]];
}
if(dep[x]>dep[y]) swap(x,y);
T.upd(1,1,n,dep[x],dep[y],1);
}
int query_P(ll x,ll y){
ll res=0;
while(tp[x]!=tp[y]){
if(dep[tp[x]]<dep[tp[y]]) swap(x,y);
res=cal(res+T.query(1,1,n,dfn[tp[x]],dfn[x]));
// cout<<T.query(1,1,n,dfn[tp[x]],dfn[x])<<endl;
x=f[tp[x]];
}
if(dep[x]>dep[y]) swap(x,y);
res=cal(res+T.query(1,1,n,dfn[x],dfn[y]));
// cout<<res<<endl;
return res;
}
int main() {
memset(hson,-1,sizeof(hson));
cin>>n>>m;
for(ll i=2;i<=n;i++){
int x;cin>>x;x++;
G[x].push_back(i);
f[i]=x;
}
dep[1]=1,dfs1(1,0),dfs2(1,1);
// for(int i=1;i<=n;i++) cout<<dfn[i]<<endl;
for(ll i=1;i<=m;i++){
ll l,r,z;
cin>>l>>r>>z;r++,z++;
q[++cnt].flag=0,q[cnt].x=l,q[cnt].id=i,q[cnt].z=z;
q[++cnt].flag=1,q[cnt].x=r,q[cnt].id=i,q[cnt].z=z;
}
sort(q+1,q+1+cnt,cmp);
for(ll i=1;i<=cnt;i++){
for(ll j=q[i-1].x+1;j<=q[i].x;j++)
upd_P(1,j);
if(!q[i].flag) ans[q[i].id]=cal(ans[q[i].id]-query_P(1,q[i].z));
else ans[q[i].id]=cal(ans[q[i].id]+query_P(1,q[i].z));
}
for(ll i=1;i<=m;i++) cout<<ans[i]<<"\n";
return 0;
}