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 integersnn, indicating the number of node.(2≤n≤200000)(2≤n≤200000)
Next line containsnnintegers where theii-th integer represents
Each of the nextn−1n−1lines contains two positive integersx,yx,y(1≤x,y≤n,x≠y)(1≤x,y≤n,x≠y), meaning an edge between nodexxand nodeyy.
It is guaranteed that these edges form a tree.
Output
For each test case, output "Case #x:y" in one line (without quotes), where
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