C++struct HLD
{
static const int N = 3e4+5,M = 6e4+5;
struct node {int to,ne,w;} edge[M];
int head[N],len;
int fa[N],dep[N],si[N],son[N],top[N],seg[N],rev[N],cnt;
int tsum[N<<2],tmax[N<<2];
HLD () : len(0) , cnt(0) {}
inline void insert(int u,int v,int w) {edge[++len] = {v,head[u],w},head[u] = len;}
inline void add(int u,int v,int w) {insert(u,v,w),insert(v,u,w);}
void dfs1(int x,int f)
{
dep[x] = dep[f]+1,fa[x] = f,si[x] = 1;
for(int i = head[x],v;i;i = edge[i].ne)
if ((v = edge[i].to) != f)
{
dfs1(v,x),si[x] += si[v];
if(si[v] > si[son[x]]) son[x] = v;
}
}
void dfs2(int x)
{
if (son[x]) seg[son[x]] = ++cnt,top[son[x]] = top[x],rev[cnt] = son[x],dfs2(son[x]);
for (int i = head[x],v;i;i = edge[i].ne)
if (!top[(v = edge[i].to)])
seg[v] = ++cnt,rev[cnt] = v,top[v] = v,dfs2(v);
}
inline int lc(int x) {return x<<1;}
inline int rc(int x) {return x<<1|1;}
inline void pushup(int x) {tsum[x] = tsum[lc(x)]+tsum[rc(x)],tmax[x] = max(tmax[lc(x)],tmax[rc(x)]);}
void build(int x,int l,int r,int *a)
{
if (l == r) return tsum[x] = tmax[x] = a[rev[l]],void();
int mid = (l+r)>>1;
build(lc(x),l,mid,a);
build(rc(x),mid+1,r,a);
pushup(x);
}
void modify(int x,int l,int r,int p,int v)
{
if (l == r) return tsum[x] = tmax[x] = v,void();
int mid = (l+r)>>1;
if (p <= mid) modify(lc(x),l,mid,p,v);
else modify(rc(x),mid+1,r,p,v);
pushup(x);
}
int query_sum(int x,int l,int r,int pl,int pr)
{
if (pl<=l && r<=pr) return tsum[x];
int mid = (l+r)>>1,res = 0;
if (pl <= mid) res += query_sum(lc(x),l,mid,pl,pr);
if (pr > mid) res += query_sum(rc(x),mid+1,r,pl,pr);
return res;
}
int query_max(int x,int l,int r,int pl,int pr)
{
if (pl<=l && r<=pr) return tmax[x];
int mid = (l+r)>>1,res = INT_MIN;
if (pl <= mid) res = max(res,query_max(lc(x),l,mid,pl,pr));
if (pr > mid) res = max(res,query_max(rc(x),mid+1,r,pl,pr));
return res;
}
int find_sum(int x,int y)
{
int fx = top[x],fy = top[y],res = 0;
while (fx != fy)
{
if (dep[fx] < dep[fy]) swap(x,y),swap(fx,fy);
res += query_sum(1,1,cnt,seg[fx],seg[x]);
x = fa[fx],fx = top[x];
}
if (dep[x] < dep[y]) swap(x,y);
return res+query_sum(1,1,cnt,seg[y],seg[x]);
}
int find_max(int x,int y)
{
int fx = top[x],fy = top[y],res = INT_MIN;
while (fx != fy)
{
if (dep[fx] < dep[fy]) swap(x,y),swap(fx,fy);
res = max(res,query_max(1,1,cnt,seg[fx],seg[x]));
x = fa[fx],fx = top[x];
}
if (dep[x] < dep[y]) swap(x,y);
return max(res,query_max(1,1,cnt,seg[y],seg[x]));
}
void init(int *a)
{
dfs1(1,0);
top[1] = seg[1] = rev[1] = cnt = 1;
dfs2(1);
build(1,1,cnt,a);
}
};