Milk Visits
InterviewTime limit1sMemory limit512 MB
Given a tree with each node labeled G or H, answer queries asking whether the path between two nodes contains at least one node of a given label.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Prefix sum, Binary search
- Solved
- No attempts yet
Problem
Farmer John is planning to build () farms that will be connected by roads, forming a tree. That is, all farms are reachable from each other, and there are no cycles. Each farm contains a cow whose breed is either Guernsey or Holstein.
Farmer John's friends () often come to visit him. During a visit with friend , Farmer John will walk with his friend along the unique path of roads from farm to farm (it may be the case that ). They can also try some milk from any cow along the path they walk. Since most of Farmer John's friends are also farmers, they have very strong preferences regarding milk. Some of his friends will only drink Guernsey milk, while the remainder will only drink Holstein milk. Any of Farmer John's friends will only be happy if they can drink their preferred type of milk during their visit.
Determine whether each friend will be happy after visiting.
Input
The first line contains the two integers and .
The second line contains a string of length . The th character of the string is 'G' if the cow in the th farm is a Guernsey, or 'H' if the cow in the th farm is a Holstein.
The next lines each contain two distinct integers and (), indicating that there is a road between farms and .
The next lines contain integers , , and a character . and represent the endpoints of the path walked during friend 's visit, while is either G or H if the th friend prefers Guernsey milk or Holstein milk.
Output
Print a binary string of length . The th character of the string should be '1' if the th friend will be happy, or '0' otherwise.
Hint
Here, the path from farm 1 and farm 4 involves farms 1, 2, and 4. All of these contain Holsteins, so the first friend will be satisfied while the second one will not.