原题链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=56&mosmsg=Submission+received+with+ID+15985977
题目大意:
把n张叠在一起的饼按从小到大排序,每次只能把 1到 k (k<=n)的饼翻转,输出每次翻转 n-k+1的值。
分析:
有三种情况:
1.饼的位置恰好在正确的位置
2.饼的位置在最上面
3.饼的位置在除上面两种情况的任意位置
可以很容易得到让第k个饼到正确位置的步骤为:3→2→1
过程:由大到小,依次调整。
代码如下:
#include<iostream>
#include<stack>
#include<deque>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>
#include<sstream>
using namespace std;
int main()
{
for (string str; getline(cin, str); cout << 0 << endl)
{
cout << str << endl;
deque<int>pic;
stringstream ss(str);
for (int x; ss >> x; pic.push_front(x)); //逆序存储
for (deque<int>::iterator it = pic.begin(); it != pic.end(); it++)
{
deque<int>::iterator max = max_element(it, pic.end());//it前面的饼位置已经正确。所以从it到pic。end()之中找最大的
if (max != it) //是否是正确的位置
{
if (max != pic.end() - 1) //是否是最上面
{
reverse(max, pic.end());
cout << distance(pic.begin(), max) + 1 << ' ';
}
reverse(it , pic.end());
cout << distance(pic.begin(), it) + 1<<' ';
}
}
}
return 0;
}