https://www.luogu.org/problemnew/show/P2664

 #include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
struct E
{
int to,nxt;
}e[];
int f1[],ne;
int sz[],a[];
int n;
ll t1[],t2[],s,ans[];
void dfs1(int u,int fa)
{
sz[u]=;
int v;
ll t=t1[a[u]],z=t1[a[fa]];
for(int k=f1[u];k;k=e[k].nxt)
if(e[k].to!=fa)
{
v=e[k].to;
dfs1(v,u);
sz[u]+=sz[v];
}
t1[a[u]]=t+sz[u];
t2[u]=t1[a[fa]]-z;
}
void dfs2(int u,int fa)
{
int v;ll ta;
ans[u]=s;
for(int k=f1[u];k;k=e[k].nxt)
if(e[k].to!=fa)
{
v=e[k].to;
ta=t1[a[v]];
s+=n-t1[a[v]];
t1[a[v]]=n;
s+=t2[v]-sz[v];
t1[a[u]]+=t2[v]-sz[v];
dfs2(v,u);
s+=ta-t1[a[v]];
t1[a[v]]=ta;
s-=t2[v]-sz[v];
t1[a[u]]-=t2[v]-sz[v];
}
}
int main()
{
int i,x,y;
scanf("%d",&n);
for(i=;i<=n;++i)
scanf("%d",a+i);
for(i=;i<n;++i)
{
scanf("%d%d",&x,&y);
e[++ne].to=y;e[ne].nxt=f1[x];f1[x]=ne;
e[++ne].to=x;e[ne].nxt=f1[y];f1[y]=ne;
}
dfs1(,);
for(i=;i<=;++i)
s+=t1[i];
dfs2(,);
for(i=;i<=n;++i)
printf("%lld\n",ans[i]);
return ;
}

最新文章

  1. js 判断 是否位数字
  2. Android之数据库升级onUpgrade降级onDowngrade
  3. 几个常见Win32 API函数
  4. 微信公众号token的asp.net脚本
  5. (转载)PHP解析URL并得到URL中的参数
  6. Devexpress 汉化 代码 zt
  7. SQL优化 总结 精简
  8. STL笔记之【map之移除元素】
  9. int float double 最小值与最大值
  10. Django+Bootstrap+Mysql 搭建个人博客(五)
  11. HBase &#183; 印象
  12. python学习第二次笔记
  13. 关于matlab2018a版本错误使用 svmclassify 分类器
  14. Educational Codeforces Round 25
  15. HAProxy 参数配置
  16. [转].Python中sorted函数的用法
  17. Cross-origin plugin content from must have a visible size larger than 400 x 300 pixels, or it will be blocked. Invisible content is always blocked.
  18. LOJ#2427. 「POI2010」珍珠项链 Beads
  19. Javascript 计算字符串所占字节数
  20. 反转ListBox的ListBoxItem(控件级别,不是数据的反转)

热门文章

  1. laravel基础课程---14、表单验证(lavarel如何进行表单验证)
  2. window/body/img/iframe 的onload事件
  3. bzoj 1369: Gem 树形dp
  4. mac内置的FTP工具
  5. 利用正则表达式类解析SQL语句,达到Worklist兼容各个RIS数据库的目的
  6. Ubuntu——查看内存和CPU情况
  7. JMETER 定时器 之 常数吞吐量定时器
  8. Maven项目实战(1)
  9. Python 查看本机WiFi密码
  10. jquery中对于批量deferred的处理