HDU 6035---Colorful Tree(树形DP)
2018-06-17 22:09:38来源:未知 阅读 ()
题目链接
The path between each two different nodes is unique, of which we define the value as the number of different colors appearing in it.
Calculate the sum of values of all paths on the tree that has n(n−1)2 paths in total.
For each test case, the first line contains one positive integers n, indicating the number of node. (2≤n≤200000)
Next line contains n integers where the i-th integer represents ci, the color of node i. (1≤ci≤n)
Each of the next n−1 lines contains two positive integers x,y (1≤x,y≤n,x≠y), meaning an edge between node x and node y.
It is guaranteed that these edges form a tree.
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <vector> using namespace std; typedef long long LL; const int N=200005; int c[N],sum[N],sz[N]; vector<int> t[N]; LL ans; int dfs(int u,int pa) { sz[u]=1; int cn=t[u].size(); for(int i=0;i<cn;i++) { int v=t[u][i]; if(v==pa) continue; int r=sum[c[u]]; sz[u]+=dfs(v,u); int o=sum[c[u]]-r; ans+=(LL)(sz[v]-o)*(LL)(sz[v]-o-1)/2; sum[c[u]]+=sz[v]-o; } sum[c[u]]++; return sz[u]; } int main() { ///cout << "Hello world!" << endl; int n,Case=1; while(scanf("%d",&n)!=EOF) { memset(sum,0,sizeof(sum)); for(int i=1;i<=n;i++){ scanf("%d",&c[i]); t[i].clear(); } for(int i=1;i<n;i++) { int u,v; scanf("%d%d",&u,&v); t[u].push_back(v); t[v].push_back(u); } ans=0; dfs(1,-1); for(int i=1;i<=n;i++) { ans+=(LL)(n-sum[i])*(LL)(n-sum[i]-1)/2; } ans=(LL)n*(LL)(n-1)*(LL)n/2-ans; printf("Case #%d: %lld\n",Case++,ans); } return 0; }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- HDU-2955-Robberies(0-1背包) 2020-03-30
- Maximum White Subtree 2020-03-26
- hdu1455 拼木棍(经典dfs) 2020-02-29
- STL中_Rb_tree的探索 2020-02-20
- 二叉树(5)HuffmanTree 2020-02-19
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash