#include <bits/stdc++.h>
#define LL long long
#define N 200005
using namespace std;
struct Edge{int to,nxt;}edge[N<<1];
LL ans[N],head[N],a[N],n,sum[N],s[N];
void ada(int u, int v) {
static int k = 1;
edge[k] = (Edge){v, head[u]};
head[u] =k++;
}
LL ct(int x){return (LL)x*(x+1)/2;}
void dfs(int u,int fa){
s[u]=1;
int t=sum[a[u]];
for(int i=head[u];i;i=edge[i].nxt)if(edge[i].to != fa) {
int v=edge[i].to;
sum[a[u]]=0,dfs(v,u),s[u]+=s[v],ans[a[u]]-=ct(s[v]-sum[a[u]]);
}sum[a[u]]=t+s[u];
}
int main() {
scanf("%d", &n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
ada(u,v),ada(v,u);
}
dfs(1,0);
for(int i=1;i<=n;i++)printf("%lld\n",ans[i]+ct(n)-ct(n-sum[i]));
}
[ABC163F] path pass i
最新推荐文章于 2024-11-08 23:36:48 发布