Colorful Tree(树形dp)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6035
题意:给你一棵树,树上的点有颜色,一条路径的权值为这条路径上颜色的种类,求树上所有路径的权值和。
Input
The input contains multiple test cases.
For each test case, the first line contains one positive integers nn, indicating the number of node. (2≤n≤200000)(2≤n≤200000)
Next line contains nn integers where the ii-th integer represents cici, the color of node ii. (1≤ci≤n)(1≤ci≤n)
Each of the next n−1n−1 lines contains two positive integers x,yx,y (1≤x,y≤n,x≠y)(1≤x,y≤n,x≠y), meaning an edge between node xx and node yy.
It is guaranteed that these edges form a tree.
Output
For each test case, output "Case #x: y" in one line (without quotes), where xx indicates the case number starting from 11 and yy denotes the answer of corresponding case.
Sample Input
3
1 2 1
1 2
2 3
6
1 2 1 3 2 1
1 2
1 3
2 4
2 5
3 6
Sample Output
Case #1: 6
Case #2: 29
思路:我们考虑每一种颜色对答案的贡献,一种颜色对答案的贡献等于经过这种颜色的路径数量,也就是总路径数减掉不经过这种颜色的路径数。
那么我们就可以考虑树形dp

浙公网安备 33010602011771号