Bracket Tree
Practice
4 (1 votes)
Dynamic programming
Data structures
Trees
Lowest common ancestor
Problem
72% Success 95 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code

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 \(N - 1\) 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 <= 10^5\)) - the number of vertices. 

This is followed by \(N - 1\) lines, each containing an integer, \(p_{j}\) (\(1 <= p_{j} < j\)), and a character \(c_{j}\) - the parent of vertex \(j\), and the type of bracket on the edge going from \(p_{j}\) 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 <= 10^5)\) - the number of queries. 

The following \(Q\) lines contain two integers \(u\) (\(1 <= u <= n\)), and \(v\) (\(1 <= v <= n\)), \(u \neq v\) - 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

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
7 votes
Tags:
Dynamic ProgrammingXORImplementationTreeTreesCombinatoricsData StructuresLowest Common AncestorMathematics
Points:50
5 votes
Tags:
Data StructuresLowest Common AncestorTreesLCA
Points:50
1 votes
Tags:
LoopsData StructuresCentroid decompositionTreeMedium-Hard