#P9039. Tree Color Propagation
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:
- An integer
n
(\(1 \le n \le 10^5\)) representing the number of nodes in the tree. n - 1
lines each containing two integersu
andv
(1-indexed) which denote an edge between nodesu
andv
.- A single line containing a string of length
n
composed only of the charactersR
andB
, 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>