Question: to give a pile of randomly stacked pancakes, the diameter should be arranged in the ascending order from top to bottom to the order of turning.
Idea: greedy.
1. Read pancake data, create an array, copy data, and sort data as a reference.
2. Check whether the pancake with the maximum diameter (maxnum) is at the bottom layer.
3. If it is not at the bottom layer and it is not at the top layer, all the pancakes will be turned over on the top layer, so that the largest diameter pancake to be operated will be placed at the bottom.
4. If it is neither at the underlying layer nor at the top layer, find it, first go to the top layer, and then follow the same steps as step 3.
Until maxnum represents a pancake with the smallest diameter of data.
Code:
# Include <iostream> # include <cstring> # include <cstdio> # include <cstdlib> # include <algorithm> using namespace STD; # define maxn 110 class flapjacks {PRIVATE: int jacks [maxn]; int ansjack [maxn + maxn]; int ansloop; public: void Init (); void process (); void reserv (int A [], int num); // reverse the array operation. Num is the reverse position void output () ;}; void flapjacks: reserv (int A [], int num) {int temparry [num]; for (INT loop1 = num-1, loop2 = 0; Loop1> = 0; loop1 --) {temparry [loop2 ++] = A [loop1] ;}for (INT loop1 = 0; loop1 <num; loop1 ++) {A [loop1] = temparry [loop1] ;}} void flapjacks: Init () {memset (jacks, 0, sizeof (jacks);} void flapjacks :: process () {int loop = 0, N; char C; while (scanf ("% d % C", & N, & C )! = EOF) {If (C! = '\ N') {printf ("% d", n); jacks [loop ++] = N;} else {jacks [loop ++] = N; cout <n <Endl; int clon [maxn], maxnum; For (INT I = 0; I <loop; I ++) CLON [I] = jacks [I]; sort (Clon, clon + loop); ansloop = 0; ansjack [0] = 0; For (INT I = loop-1; I >= 0; I --) {maxnum = clon [I]; // The maxnum record if (maxnum = jacks [I]) {continue ;} else {If (jacks [0] = maxnum) {// reserv (jacks, I + 1) when the pancake to be operated is at the top ); // reverse ansjack [ansloop ++] = loop-I;} else {for (Int J = 0; j <loop; j ++) from loop-I) {// If (jacks [J] = maxnum) {reserv (jacks, J + 1) when the pancake to be operated is not at the top ); ansjack [ansloop ++] = loop-J; break ;}} reserv (jacks, I + 1); ansjack [ansloop ++] = loop-I ;}}} output (); loop = 0; Init () ;}} void flapjacks: output () {for (INT I = 0; I <ansloop; I ++) {cout <ansjack [I] <"" ;}cout <0 <Endl ;}int main () {// # ifndef online_judge // freopen ("D: \ acm.txt "," r ", stdin); // # endif // online_judge flapjacks; flapjacks. process (); Return 0 ;}
Ultraviolet A 120 stacks of flapjacks