[LNOI2014]LCA(树剖+线段树)
\(\%\%\% Fading\) 此题是他第一道黑题(我的第一道黑题是蒲公英)
一直不敢开,后来发现是差分一下,将询问离线,树剖+线段树维护即可
\(Code\ Below:\)
#include <bits/stdc++.h>
#define pii pair<int,int>
#define mp make_pair
#define F first
#define S second
#define lson (rt<<1)
#define rson (rt<<1|1)
using namespace std;
const int maxn=50000+10;
const int p=201314;
int n,m,ans[maxn],sum[maxn<<2],lazy[maxn<<2];
int head[maxn],to[maxn<<1],nxt[maxn<<1],tot;
int top[maxn],dep[maxn],siz[maxn],son[maxn],fa[maxn],id[maxn],tim;
vector<pii> in[maxn],out[maxn];
inline int read(){
register int x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch)){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
return (f==1)?x:-x;
}
inline void pushup(int rt){
sum[rt]=sum[lson]+sum[rson];
}
inline void pushdown(int rt,int len){
if(lazy[rt]){
sum[lson]=(sum[lson]+lazy[rt]*(len-(len>>1)))%p;
sum[rson]=(sum[rson]+lazy[rt]*(len>>1))%p;
lazy[lson]=(lazy[lson]+lazy[rt])%p;
lazy[rson]=(lazy[rson]+lazy[rt])%p;
lazy[rt]=0;
}
}
void update(int L,int R,int C,int l,int r,int rt){
if(L <= l && r <= R){
sum[rt]=(sum[rt]+(r-l+1)*C)%p;
lazy[rt]=(lazy[rt]+C)%p;
return ;
}
pushdown(rt,r-l+1);
int mid=(l+r)>>1;
if(L <= mid) update(L,R,C,l,mid,lson);
if(R > mid) update(L,R,C,mid+1,r,rson);
pushup(rt);
}
int query(int L,int R,int l,int r,int rt){
if(L <= l && r <= R){
return sum[rt];
}
pushdown(rt,r-l+1);
int mid=(l+r)>>1,ans=0;
if(L <= mid) ans=(ans+query(L,R,l,mid,lson))%p;
if(R > mid) ans=(ans+query(L,R,mid+1,r,rson))%p;
return ans;
}
inline void addedge(int x,int y){
to[++tot]=y;
nxt[tot]=head[x];
head[x]=tot;
}
void dfs1(int x,int f){
siz[x]=1;fa[x]=f;
dep[x]=dep[f]+1;
int maxson=-1;
for(int i=head[x],y;i;i=nxt[i]){
y=to[i];
if(y==f) continue;
dfs1(y,x);
siz[x]+=siz[y];
if(siz[y]>maxson){
maxson=siz[y];
son[x]=y;
}
}
}
void dfs2(int x,int topf){
id[x]=++tim;
top[x]=topf;
if(son[x]) dfs2(son[x],topf);
for(int i=head[x],y;i;i=nxt[i]){
y=to[i];
if(y==fa[x]||y==son[x]) continue;
dfs2(y,y);
}
}
void modify(int x){
while(top[x]!=1){
update(id[top[x]],id[x],1,1,n,1);
x=fa[top[x]];
}
update(1,id[x],1,1,n,1);
}
int ask(int x){
int ans=0;
while(top[x]!=1){
ans=(ans+query(id[top[x]],id[x],1,n,1))%p;
x=fa[top[x]];
}
ans=(ans+query(1,id[x],1,n,1))%p;
return ans;
}
int main()
{
n=read(),m=read();
int l,r,x;
for(int i=2;i<=n;i++){
x=read()+1;addedge(x,i);
}
dfs1(1,0);dfs2(1,1);
for(int i=1;i<=m;i++){
l=read()+1,r=read()+1,x=read()+1;
if(l>1) in[l-1].push_back(mp(x,i));
out[r].push_back(mp(x,i));
}
for(int i=1;i<=n;i++){
modify(i);
for(int j=0;j<in[i].size();j++) ans[in[i][j].S]=(p-ask(in[i][j].F))%p;
for(int j=0;j<out[i].size();j++) ans[out[i][j].S]=(ans[out[i][j].S]+ask(out[i][j].F))%p;
}
for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
return 0;
}