[模板]树链剖分
1 void dfs1(int k){ 2 size[k]=1;deep[k]=deep[f[k]]+1; 3 for(int i=fir[k];i;i=l[i])if(!size[to[i]]){ 4 f[to[i]]=k;dfs1(to[i]);size[k]+=size[to[i]]; 5 if(size[hson[k]]<size[to[i]])hson[k]=to[i]; 6 } 7 } 8 void dfs2(int k,int topp){ 9 top[k]=topp;dfs[k]=++num;ndfs[num]=k; 10 if(hson[k])dfs2(hson[k],topp); 11 for(int i=fir[k];i;i=l[i])if(to[i]!=hson[k]&&to[i]!=f[k])dfs2(to[i],to[i]); 12 } 13 void build(int k,int ll,int rr){ 14 tl[k]=ll;tr[k]=rr; 15 if(ll==rr){tmax[k]=w[ndfs[ll]];tsum[k]=w[ndfs[ll]];return;} 16 build(k<<1,ll,(ll+rr)>>1);build(k<<1|1,((ll+rr)>>1)+1,rr); 17 tmax[k]=max(tmax[k<<1],tmax[k<<1|1]);tsum[k]=tsum[k<<1]+tsum[k<<1|1]; 18 } 19 int ttsum(int k,int ll,int rr){ 20 if(tl[k]>=ll&&tr[k]<=rr)return tsum[k]; 21 return (ll<=tr[k<<1]?ttsum(k<<1,ll,rr):0)+(rr>=tl[k<<1|1]?ttsum(k<<1|1,ll,rr):0); 22 } 23 int ttmax(int k,int ll,int rr){ 24 if(tl[k]>=ll&&tr[k]<=rr)return tmax[k]; 25 return max((ll<=tr[k<<1]?ttmax(k<<1,ll,rr):0xc0000000),(rr>=tl[k<<1|1]?ttmax(k<<1|1,ll,rr):0xc0000000)); 26 } 27 void add(int k,int a,int b){ 28 if(tl[k]==a&&tr[k]==a){tmax[k]+=b;tsum[k]+=b;return;} 29 if(a<=tr[k<<1])add(k<<1,a,b);else add(k<<1|1,a,b); 30 tmax[k]=max(tmax[k<<1],tmax[k<<1|1]);tsum[k]=tsum[k<<1]+tsum[k<<1|1]; 31 } 32 int sum(int x,int y){register int ans=0,t; 33 while(top[x]!=top[y]){ 34 if(deep[top[x]]<deep[top[y]])t=x,x=y,y=t; 35 ans+=ttsum(1,dfs[top[x]],dfs[x]); 36 x=f[top[x]]; 37 } 38 return ans+=deep[x]>deep[y]?ttsum(1,dfs[y],dfs[x]):ttsum(1,dfs[x],dfs[y]); 39 } 40 int amax(int x,int y){register int ans=0x80000000,t; 41 while(top[x]!=top[y]){ 42 if(deep[top[x]]<deep[top[y]])t=x,x=y,y=t; 43 ans=max(ans,ttmax(1,dfs[top[x]],dfs[x])); 44 x=f[top[x]]; 45 } 46 return deep[x]>=deep[y]?max(ans,ttmax(1,dfs[y],dfs[x])):max(ans,ttmax(1,dfs[x],dfs[y])); 47 }
$Fate \ is \ Fake$