#P6150. [USACO20FEB] Clock Tree S

[USACO20FEB] Clock Tree S

Description

The design of Farmer John's new barn is quite strange: it consists of NN rooms numbered 1N1\ldots N (2N25002\leq N\leq 2\,500), and N1N-1 hallways. Each hallway connects two rooms, so that every room can reach any other room by following some sequence of hallways.

Each room in the barn contains a round clock whose face has the standard integers 1121\ldots 12 printed on it. However, these clocks have only one hand, and it always points directly at one of the numbers on the face (it never points between two numbers).

The cow Bessie wants to synchronize all the clocks in the barn so that they all point to the integer 1212. However, she is not very smart: as she walks around the barn, every time she enters a room, she moves the clock hand in that room back by one position. For example, if the clock was pointing to 55, it will now point to 66; if it was pointing to 1212, it will now point to 11. If Bessie enters the same room multiple times, she moves that room's clock each time she enters.

Compute the number of possible starting rooms such that Bessie can walk around the barn and make all clocks point to 1212. Note that Bessie does not move the clock in her starting room, but any time she enters it again later, she will move it. The clocks do not run on their own; a clock changes only when Bessie enters its room. Also, once Bessie enters a hallway, she must reach the other end of the hallway (she is not allowed to turn back halfway and return to the original room).

Input Format

The first line contains NN. The next line contains NN integers, each in the range 1121\ldots 12, describing the initial clock setting in each room. The following N1N-1 lines each contain two integers aa and bb, both in the range 1N1\ldots N, describing a hallway connecting rooms aa and bb.

Output Format

Output the number of starting rooms such that it is possible for Bessie to make all clocks point to 1212.

4
11 10 11 11
1 2
2 3
2 4
1

Hint

Sample Explanation:

In this example, Bessie can make all the clocks point to 1212 if and only if she starts from room 22 (for example, by moving to rooms 11, 22, 33, 22, and finally 44).

Subtasks:

  • Test cases 22-77 satisfy N100N\leq 100.
  • Test cases 88-1515 have no additional constraints.

Translated by ChatGPT 5