#d1305. 三进制循环
三进制循环
Ternary Cycle
Problem Description
In the magical Tree Kingdom, Jiji discovered a ternary tree with nodes, numbered . The value of any node can be one of . She likes regular rather than chaotic sequences. She wants to find a path on this tree such that, from one end of the path to the other, starting from the second node, each node's value equals the value of the previous node plus modulo .
In other words, if we turn the path into a sequence of length , then for every we must have . For example: .
Now, given this ternary tree, can you help her find the longest valid path? Output the maximum length of such a path.
Input Format
The first line contains an integer (), the number of nodes in the tree.
The next lines each contain two integers , indicating an edge between nodes and .
The next line contains integers (), the value of the -th node.
Output Format
Output one integer: the maximum length of a valid path.
Sample Input
8
1 2
1 3
2 4
2 5
3 6
5 7
5 8
2 1 1 0 2 1 2 0
Sample Output
4
Sample Explanation
