最开始的时候我在写线段树部分的时候还打了一个build,后来一想,打个球球大作战的build啊!!!有个锤子的用啊!!!
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e6+;
int n;
int e,begin[maxn],next[maxn],to[maxn],a[maxn];
int tree[maxn<<],lazy[maxn<<];
int son[maxn],father[maxn],id[maxn],cnt,deep[maxn],size[maxn],top[maxn];
int res;
inline int read(){
int s=,w=;
char ch=getchar();
while(ch<=''||ch>''){if(ch=='-')w=-;ch=getchar();}
while(ch>=''&&ch<='') s=s*+ch-'',ch=getchar();
return s*w;
}
inline void add(int x,int y){
to[++e] = y;
next[e] = begin[x];
begin[x] = e;
}
inline void pushup(int root){
tree[root] = tree[root<<]+tree[root<<|];
}
inline void pushdown(int root,int pos){
lazy[root<<] += lazy[root];
lazy[root<<|] += lazy[root];
tree[root<<] += lazy[root]*(pos-(pos>>));
tree[root<<|] += lazy[root]*(pos>>);
lazy[root] = ;
}
inline void query(int root,int l,int r,int al,int ar){
if(al <= l && ar >= r){
res += tree[root];
return;
}
if(lazy[root])pushdown(root,r-l+);
int mid = l+r>>;
if(al <= mid)query(root<<,l,mid,al,ar);
if(ar > mid)query(root<<|,mid+,r,al,ar);
}
inline void update(int root,int l,int r,int al,int ar,int k){
if(al <= l && ar >= r){
lazy[root] += k;
tree[root] += k*(r-l+);
return;
}
if(lazy[root])pushdown(root,r-l+);
int mid = l+r>>;
if(al <= mid)update(root<<,l,mid,al,ar,k);
if(ar > mid)update(root<<|,mid+,r,al,ar,k);
pushup(root);
}
inline void update_range(int x,int y,int k){
while(top[x] != top[y]){
if(deep[top[x]] < deep[top[y]])swap(x,y);
update(,,n,id[top[x]],id[x],k);
x = father[top[x]];
}
if(deep[x] > deep[y])swap(x,y);
update(,,n,id[x],id[y],k);
}
inline void dfs1(int x,int fa,int dep){
deep[x] = dep;
father[x] = fa;
size[x] = ;
int maxson = -;
for(int i = begin[x];i;i = next[i]){
int y = to[i];
if(y == fa)continue;
dfs1(y,x,dep+);
size[x] += size[y];
if(size[y] > maxson)son[x] = y,maxson = size[y];
}
}
inline void dfs2(int x,int topf){
id[x] = ++cnt;
top[x] = topf;
if(!son[x])return;
dfs2(son[x],topf);
for(int i = begin[x];i;i = next[i]){
int y = to[i];
if(y == father[x] || y == son[x])continue;
dfs2(y,y);
}
}
int main(){
n = read();
for(int i = ;i <= n;i++)a[i] = read();
for(int i = ,x,y;i < n;i++){
x = read();
y = read();
add(x,y);
add(y,x);
}
dfs1(,,);
dfs2(,);
for(int i = ;i < n;i++){
update_range(a[i],a[i+],);
update_range(a[i+],a[i+],-);
}
for(int i = ;i <= n;i++)res = ,query(,,n,id[i],id[i]),printf("%d\n",res);
return ;
}