Problem 586
Validate Stack Sequences
Medium · 20 pts · Stack, Simulation
Problem
You are given two sequences PUSHED and POPPED, each a permutation of the same N distinct values. Starting with an empty stack, you must push the values in the order of PUSHED, and you may pop at any moment. Decide whether some interleaving of pushes and pops produces exactly the sequence POPPED. Simulate greedily: push each value, then keep popping while the top of the stack equals the next value to pop. The sequences are valid if the stack ends up empty.
Input
The first line contains N. The second line contains PUSHED. The third line contains POPPED.
Output
Print YES if POPPED can be produced, otherwise NO.
Constraints
1 <= N <= 1000; values are distinct, 0 <= value <= 1000; POPPED is a permutation of PUSHED
Example input
5 1 2 3 4 5 4 5 3 2 1
Example output
YES
Explanation
Push 1 2 3 4, pop 4, push 5, then pop 5 3 2 1. This produces exactly the popped order 4 5 3 2 1, so the answer is YES.