树链剖分详解 - 自为风月马前卒 - 博客园 (cnblogs.com)
P3384 【模板】重链剖分/树链剖分 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<iostream>
using namespace std;void dfs1(int u,int father){
fa[u]=father;
dep[u]=dep[father]+1;
sz[u]=1;for(int i=head[u];~i;i=edge[i].next){int v=edge[i].to;sif(v==father)continue;dfs1(v,u);if(sz[son[u]<=sz[v])son[u]=v;
}}//每个dfs完成3个初始化
void dfs2(int u,int t){//重编号top[u]=t;idx[u]=++cnt;a[cnt]=b[u];if(!son[u])return ;dfs(son[u],t);//重儿子链首相同for(int i=head[u];~i;i=edge[i].next){ int v=edge[i].to;if(!idx[v])//现在idx是独一无二的时间戳{dfs(v,v);}}}struct tree{
int l,r,w,
}tr[];
void bui(int id,int l,int r){
tr[id]={l,r,0,a[r]};
if(l==r)return ;bui(ls,l,mid);
bui(rs,mid+1,r);
pushup(id);}void pushup(int id){
tr[id].sum+=tr[ls].sum+tr[rs].sum;
}ll query(int id,int x,int y){
if(x<=tr[id].l&&y>=tr[id].r){return tr[id].sum;}
pushdown(id);ll res=0;
if(l<=mid)res+=query(ls,x,y);
if(r>=mid+1)res+=query(rs,x,y);return res;}ll querypath(int u,int v){while(top[u]!=top[v]){if(dep[top[u]]<=top[v])swap(u,v);res+=query(1,idx[top[u]],idx[u]);u=fa[top[u]];
}if(dep[u]<dep[v])swap(u,v);
res+=query(1,idx[v],idx[u]);return res;}