I just simulate the flipping. we are not required to find the optimal solution, so I choose a way easy to understand. I find the biggest cake in the unsorted stack, and then check its position. if it is at the bottom of the stack, then nothing need to be done. otherwise, at most two steps are needed to flip it to the bottom of the unsorted Stack: one flips it to the top, the other flips it to the bottom. repeat until the unsorted stack shrinks to none.
Code:
- /*************************************** **********************************
- * Copyright (c) 2008 by liukaipeng *
- * Liukaipeng at gmail dot com *
- **************************************** *********************************/
- /* @ Judge_id 00000 120 C ++ "stacks of flapjacks "*/
- # Include <algorithm>
- # Include <deque>
- # Include <fstream>
- # Include <iostream>
- # Include <iterator>
- # Include <list>
- # Include <map>
- # Include <queue>
- # Include <set>
- # Include <sstream>
- # Include <stack>
- # Include <string>
- # Include <vector>
- Using namespace STD;
- Int const cakecount = 31;
- Int flip_sort (int * cakes, int ncakes, int flips [])
- {
- Int sorted [cakecount];
- Copy (cakes, cakes + ncakes, sorted );
- Sort (sorted, sorted + ncakes );
- Int nflips = 0;
- For (INT I = ncakes-1; I> = 0; -- I ){
- Int P = I;
- For (; P> = 0 & cakes [p]! = Sorted [I]; -- p ){}
- If (P = I) continue;
- If (P! = 0 ){
- Flips [nflips ++] = ncakes-P;
- For (Int J = 0, K = P; j <K; ++ J, -- K)
- Cakes [J] ^ = cakes [K], cakes [k] ^ = cakes [J], cakes [J] ^ = cakes [k];
- }
- Flips [nflips ++] = ncakes-I;
- For (Int J = 0, K = I; j <K; ++ J, -- K)
- Cakes [J] ^ = cakes [K], cakes [k] ^ = cakes [J], cakes [J] ^ = cakes [k];
- }
- Flips [nflips ++] = 0;
- Return nflips;
- }
- Int main (INT argc, char * argv [])
- {
- # Ifndef online_judge
- Filebuf In, out;
- Cin. rdbuf (in. Open (string (argv [0]) + ". In"). c_str (), ios_base: In ));
- Cout. rdbuf (out. Open (string (argv [0]) + ". Out"). c_str (), ios_base: Out ));
- # Endif
- String line;
- While (Getline (CIN, line )){
- Stringstream SS (line );
- Int cakes [cakecount];
- Int ncakes = 0;
- For (; SS> cakes [ncakes]; ++ ncakes ){}
- For (INT I = 0; I <ncakes; ++ I)
- Cout <(I> 0? "": "") <Cakes [I];
- Cout <'/N ';
- Int flips [cakecount];
- Int nflips = flip_sort (cakes, ncakes, flips );
- For (INT I = 0; I <nflips; ++ I)
- Cout <(I> 0? "": "") <Flips [I];
- Cout <'/N ';
- }
- Return 0;
- }