提交时间:2022-07-20 11:51:20
运行 ID: 52731
#include<cstdio> #include<queue> using namespace std; typedef long long ll; const ll mod=1e9+7; const int N=5e5+5; int n; int a[N]; struct node{ int to,nxt; }e[N<<1]; int head[N],cnt; inline void add(int u,int v){ e[++cnt].to=v; e[cnt].nxt=head[u]; head[u]=cnt; } struct fruit{ int pos,val; friend bool operator<(fruit x,fruit y){ return x.val>y.val; } }; ll ans; bool vis[N]; bool vg[N]; int stk[N],sze; priority_queue<fruit> q; inline void dfs(int f,int u){ for(int i=head[u];i;i=e[i].nxt){ int v=e[i].to; if(v==f) continue; q.push(fruit{v,a[v]}); if(!vis[v]){ ll ct=0; sze=0; while(!q.empty()){ fruit h=q.top(); q.pop(); if(vg[h.pos]) continue; stk[sze++]=h.pos; ++ct; ans=(ans+ct*h.val)%mod; } while(sze--) q.push(fruit{stk[sze],a[stk[sze]]}); } dfs(u,v); vg[v]=1; } } inline int read(){ int x=0,ch=getchar(); while(ch<48||ch>57) ch=getchar(); while(ch>47&&ch<58) x=(x<<3)+(x<<1)+(ch&15),ch=getchar(); return x; } int main(){ // freopen("tree.in","r",stdin); n=read(); for(int i=1;i<=n;++i) a[i]=read(); for(int i=1,u,v;i<n;++i){ u=read(),v=read(); add(u,v); add(v,u); } for(int i=1;i<n;++i){ q.push(fruit{i,a[i]}); dfs(0,i); for(int j=1;j<=n;++j) vg[j]=0; vis[i]=1; while(!q.empty()) q.pop(); } for(int i=1;i<=n;++i) ans+=a[i]; ans%=mod; printf("%lld\n",ans); return 0; }