提交时间:2022-07-20 11:51:33
运行 ID: 52741
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN=2005,mod=1000000007; struct Edge { int v,next; } edge[MAXN<<1]; ll ans,siz[MAXN]; int head[MAXN],ecnt,n,fa[MAXN][12],a[MAXN],b[MAXN],m,s[MAXN<<1],t,l[MAXN],r[MAXN],dep[MAXN]; void addedge(int u,int v) { edge[++ecnt].v=v,edge[ecnt].next=head[u],head[u]=ecnt; } void dfs(int u) { for(int j=1; j<=11; ++j)fa[u][j]=fa[fa[u][j-1]][j-1]; ll ss=0; siz[u]=1,s[++t]=u,l[u]=t; for(int i=head[u],v; i; i=edge[i].next) { v=edge[i].v; if(v==fa[u][0])continue; fa[v][0]=u,dep[v]=dep[u]+1,dfs(v),siz[u]+=siz[v]; ss+=siz[v]*(siz[v]-1); s[++t]=u; } r[u]=t; ss+=(n-siz[u])*(n-siz[u]-1); ss=(n*(n-1)-ss)/2+1; ans=(ans+ss*b[a[u]])%mod; } int solve(int u,int v) { int d=dep[u]-dep[v]-1; for(int i=0; d; ++i,d>>=1)if(d&1)u=fa[u][i]; return u; } int main() { scanf("%d",&n); for(int i=1; i<=n; ++i)scanf("%d",&a[i]),b[i]=a[i]; sort(b+1,b+n+1); for(int i=1; i<=n; ++i)a[i]=lower_bound(b+1,b+n+1,a[i])-b; for(int i=1,u,v; i<n; ++i) { scanf("%d%d",&u,&v); addedge(u,v),addedge(v,u); } dfs(1); for(int i=1; i<n; ++i) for(int j=i+1; j<=n; ++j) if(l[i]<=l[j]&&r[j]<=r[i])ans=(ans+(n-siz[solve(j,i)])*siz[j]%mod*max(b[a[i]],b[a[j]]))%mod; else if(l[j]<=l[i]&&r[i]<=r[j])ans=(ans+(n-siz[solve(i,j)])*siz[i]%mod*max(b[a[i]],b[a[j]]))%mod; else ans=(ans+siz[i]*siz[j]%mod*max(b[a[i]],b[a[j]]))%mod; printf("%lld\n",ans); return 0; }