牛客网-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
#include
#include
#include
#include
#include
#include
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;
		
	}
}

你可能感兴趣的:(牛客网机试)