Two-Stacks Solitaire
Time limit1sMemory limit128 MB
Given a stock pile dealt in order, decide whether the top card can be moved to intermediate pile 1 or 2 or popped to the foundation so all cards end non-decreasing.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Stack, Greedy, Simulation
- Solved
- No attempts yet
Problem
Card games for a single player are called patience in Britain and solitaire in the United States. One notoriously difficult solitaire game is called Two-Stacks and uses the following layout and rules.
- Layout. The table holds a stock pile, two intermediate piles, and one foundation pile.
- Cards. A game may use up to four complete decks, or parts of them. A complete deck has cards; ignoring suits and faces, we label the cards with the numbers to , so each value appears at most four times.
- Dealing. The chosen cards are dealt face up, one on top of another, forming the stock pile. The first card dealt ends up at the bottom and the last card dealt ends up on top.
- Moves. Cards move one at a time, and only the topmost card of a pile may be moved. A
push xmoves the topmost card of the stock pile onto intermediate pile (where is or ); apop xmoves the topmost card of intermediate pile onto the foundation pile. - Goal. You win when every card used in the game sits on the foundation pile in non-decreasing order from bottom to top.
Your grandmother has just learned the game and, for each deal she tries, wants to know whether it can be won at all. Write a program that decides this for her.
Input
The input contains several test cases. The first line of a test case has a single integer (), the number of cards in the game. The second line has integers between and , separated by single spaces, listing the cards in dealing order; the topmost card of the stock pile is therefore the -th number on the line. Each value from to appears at most four times in a test case. The input ends with a test case where , which must not be processed.
Output
For each test case, first print a line with its identifier in the form #i, where starts at and increases by one for every test case. Then print a single line: possible if the deal can be won (every card can be moved onto the foundation pile in non-decreasing order using the two intermediate piles), or impossible otherwise.