题目大意:给出一个字符串,可以将第 i 个之前的头尾翻转,要求最后结果从小到大,输出翻转过程。
解题思路:通过将最大值翻转,翻到第一位,然后翻转最后一位,这样可以将最大的放到最后一位。找出当前未排序的当中的最大值,判断是否位于正确的位置,不是的话将它翻转到第一位(如果已经是第一位就不用),然后翻转到正确位置即可。puts 输出就会 WA 不知道为什么。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<stdlib.h>
#include<cmath>
using namespace std;
int d[100];
int tot;
void swap(int n) {
for(int i = 0; i < (n+1)/2; i++) {
int t = d[n-i];
d[n-i] = d[i];
d[i] = t;
}
printf("%d ", tot - n);
}
int main() {
while(scanf("%d", &d[0]) != EOF) {
tot = 1;
while(1) {
if(getchar() != ' ')break;
scanf("%d", &d[tot++]);
}
printf("%d", d[0]);
for (int i = 1; i < tot; i++)
printf(" %d", d[i]);
printf("\n");
for (int i = 0; i < tot; i++) {
int max = d[0], tag = 0;
for (int j = 0; j < tot - i; j++) {
if (d[j] >= max) { max = d[j]; tag = j;}
}
if (tag != tot-i-1) {
if (tag != 0) swap(tag);
swap(tot-i-1);
}
}
printf("0\n");
}
return 0;
}