ENG  RUSTimus Online Judge
Online Judge
Online contests
About Online Judge
Frequently asked questions
Site news
Problem set
Submit solution
Judge status
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests

Open Ural SU Championship 2010

About     Problems     Submit solution     Judge status     Standings
Contest is over

K. Rounders

Time limit: 0.5 second
Memory limit: 64 MB
After the shameful loss in the match against Jesus Quintana, The Dude, Donny and Walter decided to turn to poker and become rounders. First of all, they decided to learn to deal with cards.
Walter gave Donny a simple task—he should split a deck of 52 cards into four piles in such a way that cards in each pile would be sorted in the order of ascending value. Two should be the topmost card, three should be the next card and so on. Ace should lie in the bottom. Walter wanted all decks to be comprised of the cards of the same suit but he forgot to mention it. As a result, the suits in piles were shuffled.
The Dude decided to save the day. But after five White Russians he poured into himself yesterday he isn't in a good condition for thinking. In fact, he is able to perform only the following actions:
  • take a few cards of one suit from the top of a deck and create a new deck of them;
  • take a few cards of one suit from the top of a deck and put them onto a card which value is greater by one than the value of the bottommost of the taken cards.
The Dude doesn't change the order of cards while moving them.
Help The Dude to complete Walter's task before Walter get insane and shoot both his best friends with Uzi.


The input consists of four lines describing the piles of cards. Each line contains the description of 13 cards in a pile in order from top to bottom (that is, in the order of ascending values). Each card is denoted by its value and its suit. The value is one of the following: 2, 3, …, 9, T (ten), J (jack), Q (queen), K (king), A (ace), the suit can be: S (spades), C (clubs), D (diamonds) or H (hearts). All cards in the input are different.


Output the minimal number of operations The Dude should perform in order to obtain four piles consisting of cards with the same suit.


2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC AC
2S 3S 4S 5S 6S 7S 8D 9D TD JD QD KD AD
2D 3D 4D 5D 6D 7D 8S 9S TS JS QS KS AS
2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH AH
Problem Author: Alexander Ipatov
Problem Source: XV Open USU Championship
To submit the solution for this problem go to the Problem set: 1784. Rounders