Citadel Hierarchy
InterviewTime limit1sMemory limit1024 MB
Given a rooted tree of Ricks with Mortys as leaves, decide whether each Rick can reorder its direct subordinates so the bottom-level Mortys end up sorted.
- Level
Medium5 of 10
- Topics
- Tree, DFS, Implementation
- Solved
- No attempts yet
Problem
As is well known, the Citadel of Ricks is home to countless Ricks and Mortys: exactly Ricks and Mortys. To keep the new Citadel from descending into total chaos, it was decided to build a clear hierarchy that makes it possible to quickly determine who is to blame for any incident.
First, the Ricks are numbered from 1 to in decreasing order of importance. The Mortys are numbered from 1 to in increasing order of unimportance. The hierarchy is drawn as a rooted tree with these properties:
- The tree has exactly internal vertices and leaves, and all leaves are at the same depth.
- All internal vertices are occupied by Ricks, and all leaves are occupied by Mortys. All Mortys must be at the bottom of the hierarchy.
- Ricks on any level have smaller numbers than Ricks on the levels below. In particular, the root holds the Supreme Rick, number 1.
- On each level, the Ricks are numbered in increasing order from left to right.
- Every Rick on the levels up to the second-to-last level has at least two direct subordinates.
The Ricks built this hierarchy quickly. The Mortys, in a panic, lined up on the bottom level in a random order. Seeing this chaos, the Ricks decided that since they do not like rules much anyway, the rule that Ricks on each level must be ordered can be dropped. The Mortys on the bottom level, however, must be sorted in increasing order from left to right.
Each Rick may rearrange its direct subordinates in any way. A Rick may not change its set of subordinates (taking new ones or handing old ones to another Rick), and may not move to another level. Can the Ricks sort all the Mortys in increasing order this way? An example of a possible solution is shown below:


The initial hierarchy and the moves needed to sort the Mortys.
Input
The first line contains two integers and separated by a space ().
The second line contains distinct integers separated by spaces: the numbers of the Mortys in the order they stand in the initial hierarchy, from left to right ().
The third line contains , the numbers of the immediate superiors of Ricks numbered 2 through ().
The fourth line contains, in the same format, , the numbers of the immediate superiors of the Mortys in the order they stand in the initial hierarchy (). Note that is the superior of the Morty with number , not the Morty with number 1.
It is guaranteed that the hierarchy structure satisfies the constraints above.
Output
Print YES if the Ricks can sort all the Mortys in increasing order by swapping their direct subordinates, and NO otherwise.