Colorful Tree(树形dp)

时间:2021-08-08
本文章向大家介绍Colorful Tree(树形dp),主要包括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. (2n200000)(2≤n≤200000)

Next line contains nn integers where the ii-th integer represents cici, the color of node ii. (1cin)(1≤ci≤n)

Each of the next n1n−1 lines contains two positive integers x,yx,y (1x,yn,xy)(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

原文地址:https://www.cnblogs.com/lsl127/p/13583804.html