紫书 例题8-1 UVa 120(构造法)

#include<cstdio>
#include<iostream>
#include<sstream>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 50;
int a[MAXN], n;

void filp(int pos)   //学习这里翻转的写法 
{
	REP(i, 0, pos - i)
		swap(a[i], a[pos-i]);
	printf("%d ", n - pos);
}

int main()
{
	string s;
	while(getline(cin, s))
	{
		cout << s << endl;
		stringstream ss(s);
		n = 0;
		while(ss >> a[n]) n++;
		for(int i = n - 1; i > 0; i--)
		{
			int pos = max_element(a, a + i + 1) - a;  //max_element表示查找最大值 
			if(pos == i) continue;   //已经在该在的位置的时候就不用翻了 
			if(pos > 0) filp(pos);  //如果已经在顶就不用翻到顶上 
			filp(i);                //从顶上翻下来 
		}
		puts("0");
	}
	return 0;
}

原文地址:https://www.cnblogs.com/sugewud/p/9819600.html