树链剖分基础题,路径权值修改+差分
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e5+;
int hd[N],ne,n,m,a[N],fa[N],son[N],dep[N],siz[N],top[N],dfn[N],rnk[N],tot,c[N];
struct E {int v,nxt;} e[N<<];
void addedge(int u,int v) {e[ne]= {v,hd[u]},hd[u]=ne++;}
void dfs1(int u,int f,int d) {
fa[u]=f,son[u]=,dep[u]=d,siz[u]=;
for(int i=hd[u]; ~i; i=e[i].nxt) {
int v=e[i].v;
if(v==fa[u])continue;
dfs1(v,u,d+),siz[u]+=siz[v];
if(siz[v]>siz[son[u]])son[u]=v;
}
}
void dfs2(int u,int tp) {
top[u]=tp,dfn[u]=++tot,rnk[dfn[u]]=u;
if(!son[u])return;
dfs2(son[u],top[u]);
for(int i=hd[u]; ~i; i=e[i].nxt) {
int v=e[i].v;
if(v==fa[u]||v==son[u])continue;
dfs2(v,v);
}
}
void upd(int u,int v) {
for(; top[u]!=top[v]; u=fa[top[u]]) {
if(dep[top[u]]<dep[top[v]])swap(u,v);
c[dfn[top[u]]]++,c[dfn[u]+]--;
}
if(dep[u]<dep[v])swap(u,v);
c[dfn[v]]++,c[dfn[u]+]--;
} int main() {
memset(hd,-,sizeof hd),ne=;
scanf("%d",&n);
for(int i=; i<n; ++i)scanf("%d",&a[i]);
for(int i=; i<n; ++i) {
int u,v;
scanf("%d%d",&u,&v);
addedge(u,v);
addedge(v,u);
}
tot=,dfs1(,,),dfs2(,);
for(int i=; i<n-; ++i)upd(a[i],a[i+]);
for(int i=; i<=tot; ++i)c[i]+=c[i-];
for(int i=; i<n; ++i)c[dfn[a[i]]]--;
for(int i=; i<=n; ++i)printf("%d\n",c[dfn[i]]);
return ;
}