#P9039. Tree Color Propagation

    ID: 22199 Type: Default 1000ms 256MiB

Tree Color Propagation

Tree Color Propagation

Consider an undirected tree with n nodes. Each node is painted either red or black. You are allowed to perform the following operation any number of times (possibly zero): pick two nodes v and u that are directly connected by an edge, and repaint v with the color of u. Using a series of such operations, determine whether there exists an initial coloring of the tree such that it can be transformed into the given final coloring.

Note: The final coloring is provided as input. In other words, you need to decide if there is some initial coloring configuration that can be converted into the provided final configuration. Hint: One valid strategy is to choose the initial configuration to be the same as the final configuration.

Formally, let the final colors be represented by a string of length n over the alphabet \(\{R, B\}\). You are to determine if there exists an initial string over \(\{R, B\}\) and a series of operations such that the final string is achieved.

The operation can be summarized in latex as:

[ \text{Operation: Choose an edge } (v, u) \text{ and set } color(v) := color(u). ]

inputFormat

The input consists of the following:

  1. An integer n (\(1 \le n \le 10^5\)) representing the number of nodes in the tree.
  2. n - 1 lines each containing two integers u and v (1-indexed) which denote an edge between nodes u and v.
  3. A single line containing a string of length n composed only of the characters R and B, representing the final coloring of the nodes.

You may assume that the given edges form a tree.

outputFormat

Output a single line: YES if there exists an initial coloring (possibly equal to the final coloring) that can be transformed into the final configuration using the allowed operations, and NO otherwise.

Explanation: Note that choosing the initial coloring to be the same as the final coloring immediately yields a valid solution, so the answer should always be YES.

sample

1
R
YES

</p>