牛客网-Pancake sorting

题目描述
We start with a stack n of pancakes of distinct sizes. The problem is to convert the stack to one in which the pancakes are in size order with the smallest on the top and the largest on the bottom. To do this, we are allowed to flip the top k pancakes over as a unit (so the k-th pancake is now on top and the pancake previously on top is now in the k-th position).

For example: This problem is to write a program, which finds a sequence of at most (2n - 3) flips, which converts a given stack of pancakes to a sorted stack.

我的代码

#include<stdio.h>
#include<stdlib.h>
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

int main()
{
	int k;
	while (cin>>k)
	{
		if (k == 0)
		{
			break;
		}

		int *numbers = new int[k];
		int *temp = new int[k];
		vector<int> flips;
		for (int i = 0; i < k; i++)
		{
			cin >> numbers[i];
		}
		int length = k;
		while (true)
		{
			if (length <= 0)
			{
				break;
			}
			int max = -1;
			int max_index = -1;
			for (int i = 0; i < length; i++)
			{
				if (numbers[i] > max)
				{
					max = numbers[i];
					max_index = i;
				}
			}
			if (max_index == length - 1)
			{

			}
			else if (max_index == 0)
			{
				for (int i = 0; i < length; i++)
				{
					temp[(length - 1)-i] = numbers[i];
				}
				for (int i = 0; i < length; i++)
				{
					numbers[i] = temp[i];
				}
				flips.push_back(length);
			}
			else{
				for (int i = 0; i < length; i++)
				{
					if (i <= max_index)
					{
						temp[(length - 1) - max_index + i] = numbers[i];
					}
					else
					{
						temp[(length - 1) - i] = numbers[i];
					}
					
				}
				for (int i = 0; i < length; i++)
				{
					numbers[i] = temp[i];
				}
				flips.push_back(max_index+1);
				flips.push_back(length);
			}
			length--;
			
			
		}
		//output
		cout << flips.size();
		for (int i = 0; i < flips.size(); i++)
		{
			cout << ' ' << flips[i];
		}
		cout << endl;
		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值