/* coder: ACboy date: 2010-2-27 result: AC description: UVa 120 - Stacks of Flapjacks */ #include <iostream> #include <string> #include <sstream> #include <algorithm> using namespace std; // 用于保存输入的初始化数列 int data[50]; // 用于保存目标状态的数列 int target[50]; // 检测是否已经到达目标状态 int ifEnd(int count) { int flag = 1; for (int i = 0; i < count; i++) { if (target[i] != data[i]) {flag = 0;break;} } return flag; } // 查找当前尚未到达目标状态的数列中的最大数据的位置 int findMaxPos(int count) { int max = -1; int pos = -1; for (int i = 0; i < count; i++) { if (data[i] > max) {max = data[i]; pos = i;} } return pos; } // 执行题目中的flip操作 void flip(int end) { for (int i = 0; i < end / 2; i++) { int temp = data[i]; data[i] = data[end - 1 - i]; data[end - 1 - i] = temp; } } int main() { #ifndef ONLINE_JUDGE freopen("120.txt", "r", stdin); #endif string input; while (getline(cin, input)) { cout << input << endl; istringstream in(input); int count = 0; // 保存数据 while (!in.eof()) { int temp; in >> temp; data[count++] = temp; } // 拷贝(通常使用memcpy,因为这比用循环赋值快) memcpy(target, data, sizeof(data)); sort(target, target + count); // 用total来记录数列中的数据数 int total = count; // 只要还没有到达目标状态就一直做 while (!ifEnd(count)) { // 查找最大数据在数组data中的位置 int maxPos = findMaxPos(count); // 如果最大的数据在正确的位置上则进行两次交换(flip函数)但数组的状态不变 // 所有没有调用flip函数 if (maxPos == count - 1) { cout << total - count + 1 << " " << total - count + 1 << " "; } // 如果最大的数据没有在正确的位置上,则再分两种情况 else { // 如果在第一个位置,则进行一次flip操作(如:4 1 2 3 -> 3 2 1 4) if (maxPos == 0) { flip(count); cout << total - count + 1 << " "; } // 如果不在第一个位置,则进行两次flip操作(如:1 4 3 2 -> 4 1 3 2 -> 2 3 1 4) else { flip(maxPos + 1); cout << total - maxPos << " "; flip(count); cout << total - count + 1 << " "; } } // 每执行一次while循环里面的代码,最后一个数据就在它正确的位置上,下一次执行while的语句 // 只需要对前面的数据进行调整,所有进行count--。 count--; } cout << "0" << endl; } return 0; }