Patience
Time limit2sMemory limit512 MB
Given n, count the unfinished-suit layouts with fewer than n high cards out of place that reach the ordered row.
- Level
Hard8 of 10
- Topics
- Combinatorics, Dynamic programming, Game theory
- Solved
- No attempts yet
Problem
Sasha plays a patience on a board of 14 columns and 4 rows. He takes a standard 52 card deck without jokers, pulls the four aces out of it and puts them in the first column: cell (1, 1) holds the ace of diamonds, (1, 2) the ace of hearts, (1, 3) the ace of clubs, (1, 4) the ace of spades. A cell means column and row . He shuffles the rest of the deck and deals it row by row while skipping column 2, so column 2 stays empty and columns 3 to 14 are covered by cards.
After the deal Sasha makes moves. A move selects one empty cell. The card that covers it is fixed by the cell to its left: the covering card has the same suit and the next value, in the order Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. For example, if cell (6, 3) holds the queen of spades and cell (7, 3) is empty, then selecting (7, 3) brings the king of spades there and empties the cell the king came from. If the left neighbour of an empty cell holds a king or is empty itself, that empty cell cannot be selected.
The goal is an ordered row for every suit: columns 1 to 13 hold Ace to King and column 14 is empty. If the cards are not ordered and every empty cell follows a king or another empty cell, Sasha loses. The classic rules let him reshuffle the unordered cards twice more with the ordered ones left in place, but Sasha is experienced and often wins without a reshuffle.
Sasha now wants to count. Consider the positions where three suits are already ordered and the fourth is ordered only in part: fewer than of its highest cards are out of place, so only the rightmost columns can hold unordered cards. For that means columns 1 to 11 are ordered while columns 12, 13, 14 hold the queen, the king and the empty cell in an arbitrary order. Only one of those positions is lost, [king] [empty] [queen], because the empty cell sits right after the king and cannot be selected. The other five are won.
- [queen] [king] [empty] is already the goal.
- [queen] [empty] [king] lets the king move next to the queen.
- [empty] [queen] [king] turns into position 2 once the queen moves behind the jack.
- [empty] [king] [queen] turns into the goal once the queen moves behind the jack.
- [king] [queen] [empty] turns into position 3 once the king moves into the empty cell.
So the answer for is 5. Write a program that counts the winning positions for a given between 1 and 13.
Input
The first line contains one integer ().
Output
Print one integer on a single line: the number of winning positions among the positions with fewer than highest cards of the unfinished suit out of place.