UVa Problem Solution: 120 - Stacks of Flapjacks

来源:互联网 发布:什么编程软件好用 编辑:程序博客网 时间:2024/05/16 15:43

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:
  1. /*************************************************************************
  2.  * Copyright (C) 2008 by liukaipeng                                      *
  3.  * liukaipeng at gmail dot com                                           *
  4.  *************************************************************************/
  5. /* @JUDGE_ID 00000 120 C++ "Stacks of Flapjacks" */
  6. #include <algorithm>
  7. #include <deque>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <iterator>
  11. #include <list>
  12. #include <map>
  13. #include <queue>
  14. #include <set>
  15. #include <sstream>
  16. #include <stack>
  17. #include <string>
  18. #include <vector>
  19. using namespace std;
  20.      
  21. int const cakecount = 31;
  22.           
  23. int flip_sort(int *cakes, int ncakes, int flips[])
  24. {
  25.   int sorted[cakecount];
  26.   copy(cakes, cakes + ncakes, sorted);
  27.   sort(sorted, sorted + ncakes);
  28.   int nflips = 0;
  29.   for (int i = ncakes - 1; i >= 0; --i) {
  30.     int p = i;
  31.     for (; p >= 0 && cakes[p] != sorted[i]; --p) {}
  32.     if (p == i) continue;
  33.     if (p != 0) {
  34.       flips[nflips++] = ncakes - p;
  35.       for (int j = 0, k = p; j < k; ++j, --k) 
  36.         cakes[j] ^= cakes[k], cakes[k] ^= cakes[j], cakes[j] ^= cakes[k];
  37.     }
  38.     flips[nflips++] = ncakes - i;
  39.     for (int j = 0, k = i; j < k; ++j, --k)
  40.       cakes[j] ^= cakes[k], cakes[k] ^= cakes[j], cakes[j] ^= cakes[k];
  41.   }
  42.   flips[nflips++] = 0;
  43.   return nflips;
  44. }
  45. int main(int argc, char *argv[])
  46. {
  47. #ifndef ONLINE_JUDGE
  48.   filebuf in, out;
  49.   cin.rdbuf(in.open((string(argv[0]) + ".in").c_str(), ios_base::in));
  50.   cout.rdbuf(out.open((string(argv[0]) + ".out").c_str(), ios_base::out));
  51. #endif
  52.   string line;
  53.   while (getline(cin, line)) {
  54.     stringstream ss(line);
  55.     int cakes[cakecount];
  56.     int ncakes = 0;
  57.     for (; ss >> cakes[ncakes]; ++ncakes) {}
  58.     for (int i = 0; i < ncakes; ++i)
  59.       cout << (i > 0 ? " " : "") << cakes[i];
  60.     cout << '/n';
  61.     int flips[cakecount];
  62.     int nflips = flip_sort(cakes, ncakes, flips);                  
  63.     for (int i = 0; i < nflips; ++i)
  64.       cout << (i > 0 ? " " : "") << flips[i];
  65.     cout << '/n';
  66.   }
  67.   return 0;
  68. }