提交时间:2022-07-20 11:51:22

运行 ID: 52732

#include<bits/stdc++.h> using namespace std; int n,d[500005],ft[500005]; long long a[500005],ans; vector<int>e[500005]; void bfs(int st){ queue<pair<int,int> >q; d[st]=1,q.push(make_pair(st,-114514)); while(!q.empty()){ pair<int,int>now=q.front(); q.pop(); for(int i=0;i<e[now.first].size();i++){ if(e[now.first][i]!=now.second){ q.push(make_pair(e[now.first][i],now.first)),ft[e[now.first][i]]=now.first; d[e[now.first][i]]=d[now.first]+1; } } } } long long f(int u,int v,long long ans=0){ set<pair<long long,int> >q; if(u==v)return a[u]; q.insert(make_pair(a[u],u)),q.insert(make_pair(a[v],v)); if(d[u]!=d[v]){ while(d[u]>d[v])u=ft[u],q.insert(make_pair(a[u],u)); while(d[v]>d[u])v=ft[v],q.insert(make_pair(a[v],v)); } while(u!=v)u=ft[u],q.insert(make_pair(a[u],u)),v=ft[v],q.insert(make_pair(a[v],v)); int cnt=0; for(set<pair<long long,int> >::iterator it=q.begin();it!=q.end();it++)ans=(ans+(((++cnt)*(*it).first)%1000000007))%1000000007; return ans; } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++)scanf("%lld",&a[i]); for(int i=1,u,v;i<n;i++)scanf("%d%d",&u,&v),e[u].push_back(v); bfs(1); for(int i=1;i<=n;i++)for(int j=i;j<=n;j++)ans=(ans+f(i,j))%1000000007; return printf("%lld\n",ans),0; }