一、算法分析
首先看到这个题,就要想到对子序列进行排序的做法。那么解题思路就比较清晰了,即先找到子序列,再用题上特有的操作(翻面法),将子序列排序。具体做法如下例所示:
2 4 1 5 3 6
5 1 4 2 3 6
3 2 4 1 5 6
4 2 3 1 5 6
1 3 2 4 5 6
3 1 2 4 5 6
2 1 3 4 5 6
1 2 3 4 5 6
分析:①将数组进行排序,本例排序结果为1 2 3 4 5 6,将结果放在b数组中,用于判断我们是否排序结束。
②从后向前遍历数组,跳过已经有序的部分(比如本例中的6要跳过)。
③找到无序部分的最大值,本例中找2 4 1 5 3的最大值为5,然后对最大值及其之前的序列进行翻转。(即先进行上浮操作,把最大值放在最上面)。
④再把原来的无序部分(6之前的部分)进行翻转,即本例中将5 1 4 2 3进行翻转,这样5就到了6的前面,那么5 和 6就有序了,重复执行操作,直到整个序列有序。
二、代码及注释
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<sstream>
#include<algorithm>
using namespace std;
const int maxn=55;
typedef vector<int> vet;
vet a,b;
void rev(int x,int y){
reverse(a.begin()+x,a.begin()+y);
}
int findmx(vet a,int len){ //找最大值的下标
int ans=0;
for(int k=0;k<len;k++) if(a[k]>a[ans]) ans=k;
return ans;
}
int main(){
string s;
int buf;
while(getline(cin,s)){ //采用流进行控制,即将s字符串看做是一段输入,并将其取一个新的名字(比如这里的ss)然后用cin的方式(如跳过空格等)将这段读到我们程序中的变量里
a.clear();
b.clear();
stringstream ss(s);
while(ss>>buf) a.push_back(buf);
b=a;
sort(b.begin(),b.end()); //将b看做目标状态
int len=a.size(); //题目要求输出原状态
for(vector<int>::iterator it=a.begin();it!=a.end();it++){ //输出方法:用迭代器
cout<<*it;
if(it!=a.end()-1) cout<<' ';
else cout<<endl;
}
int pos=len;
while(a!=b){
for(int i=pos-1;i>=0;i--){ //已经有序的部分就不需要动了
if(a[i]==b[i]) pos--;
else break;
}
int posi=findmx(a,pos); //对a中最大值进行上浮、下沉操作
rev(0,posi+1); //上浮
int p=len-posi;
if(p!=len) cout<<p<<' '; //这样做会把最后顶端的那个煎饼翻一下面,这样是不合理的,考虑到对算法复杂度影响不大,这里选择直接过滤掉这个错误输出。
rev(0,pos); //下沉
p=len-pos+1;
if(p!=len) cout<<p<<' ';
}
cout<<0<<endl;
}
return 0;
}
三、作者
Bowen
本文题解、代码及注释均为作者原创,转载请注明出处。
作者水平有限,若有纰漏之处,敬请斧正。