相當于是一個模擬,為了得到合適的順序,我們的策略是每次找到當前沒有被翻的里面最大的,然后把他翻到最前面,然后再翻到合適的位置。
需要判斷一下當前是否已經有序,有序就不用翻了。
如果在最開頭找到了合適的當前應該翻的應該不翻,因為最開頭不需要。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<climits>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<sstream>
#include<string>
using namespace std;typedef long long ll;
const int INF=0x3f3f3f3f;
const int MAXN=35;
int a[MAXN],tot,b[MAXN],idx,c[MAXN];bool ok()
{int t=0;for(int i=0;i<tot;i++){if(a[i]>t) t=a[i];else return false;}return true;
}void Reverse(int x)
{int tmp;for(int i=0,j=(x+1)/2;i<j;i++){tmp=a[i]; a[i]=a[x-i]; a[x-i]=tmp;}
}int main()
{string line;int tmp;while(getline(cin,line)){tot=0;stringstream ss(line);while(ss >> tmp){b[tot]=tmp;a[tot]=tmp;c[tot]=tmp;tot++;}for(int i=0;i<tot-1;i++){printf("%d ",c[i]);}printf("%d\n",c[tot-1]);sort(b,b+tot);while(!ok()){idx=tot-1;while(idx>0 && a[idx]==b[idx]){idx--;}if(idx==0) break;for(int i=0;i<idx;i++){if(a[i]==b[idx]){if(i==0)break;printf("%d ",tot-i);Reverse(i);break;}}printf("%d ",tot-idx);Reverse(idx);}printf("0\n");}return 0;
}