This page is still under construction.

Parts of this page are still being built. What you see may change.

Two-Stacks Solitaire

Time limit1sMemory limit128 MB

Summary
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 5252 cards; ignoring suits and faces, we label the cards with the numbers 11 to 5252, 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 x moves the topmost card of the stock pile onto intermediate pile xx (where xx is 11 or 22); a pop x moves the topmost card of intermediate pile xx 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 NN (1≤N≤2081 \le N \le 208), the number of cards in the game. The second line has NN integers between 11 and 5252, separated by single spaces, listing the cards in dealing order; the topmost card of the stock pile is therefore the NN-th number on the line. Each value from 11 to 5252 appears at most four times in a test case. The input ends with a test case where N=0N = 0, which must not be processed.

Output

For each test case, first print a line with its identifier in the form #i, where ii starts at 11 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.

Examples3

  1. Example 1

    Input
    4
    4 1 3 2
    4
    1 4 3 2
    4
    2 2 2 1
    0
    
    Expected output
    #1
    possible
    #2
    impossible
    #3
    possible
    
  2. Example 2

    Input
    1
    7
    0
    
    Expected output
    #1
    possible
    
  3. Example 3

    Input
    3
    1 2 3
    3
    3 2 1
    0
    
    Expected output
    #1
    possible
    #2
    possible