Bracket Tree

4

1 votes
Dynamic Programming, Data Structures, Trees, Lowest Common Ancestor
Problem

Alice was given a tree containing N vertices, numbered 1,...,N, by her dad as a present. The tree is rooted at vertex 1 and has N1 edges. Alice made an interesting task with the tree, can you solve it? 

For every edge in the tree, Alice wrote either an opening bracket (, or a closing bracket ), and now she wants you to answer some queries. She will ask Q queries, and for each query she wants you to check if the brackets on the edges in the path from u to v listed in order forms a balanced bracket sequence

For each query your program should output "YES" (without quotes) if the path from u to v forms a balanced bracket sequence and "NO" (without quotes) otherwise. 

A balanced bracket sequence is a string of just brackets that produces a correct mathematical expression when specific numbers and mathematical operations are added to it.

NOTE: In your output YES/NO should be in all uppercase. 

INPUT FORMAT

The first line of the input contains an integer N (1<=N<=105) - the number of vertices. 

This is followed by N1 lines, each containing an integer, pj (1<=pj<j), and a character cj - the parent of vertex j, and the type of bracket on the edge going from pj to j. The value of j runs through all values from 2 to n inclusive. It is guaranteed that each set of input data has a correct hanged tree with a root at the vertex 1.

The next line contains an integer, Q (1<=Q<=105) - the number of queries. 

The following Q lines contain two integers u (1<=u<=n), and v (1<=v<=n), uv - denoting the start and end of a path that needs to be checked. 

OUTPUT FORMAT 

You should answer all Q queries, hence the output should contain Q lines containing either a string YES or NO

Sample Input
7 
1 ( 
1 ) 
2 (
2 ) 
3 ( 
3 )
4
4 7 
7 4
2 3
5 6
Sample Output
YES
NO
YES
NO
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The tree below corresponds to the tree given as the sample

The path 4 -> 7 corresponds to the bracket sequence (())

The path 7 -> 4 corresponds to the bracket sequence ))((

The path 2 -> 3 corresponds to the bracket sequence () 

The path 5 -> 6 corresponds to the bracket sequence )()(

Editor Image

?