110402 Stacks of Flapjacks


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>

using namespace std;

static void GetVecFromStr(vector<int>& data, char* str)
{
	int i = 0;
	int firstDigit = -1;
	while(true)
	{
		if ((str[i] >= '0') && (str[i] <= '9'))
		{
			if (firstDigit < 0)
				firstDigit = i;
			++i;
			continue;
		}

		char originalChar = str[i];
		if (firstDigit >= 0)
		{
			str[i] = '\0';
			data.push_back(atoi(str + firstDigit));
			firstDigit = -1;
		}

		if ((originalChar == '\n') || (originalChar == '\0'))
			break;

		++i;
		continue;
	}

	size_t cnt = data.size();
	size_t mid = cnt / 2;
	for (size_t i = 0; i < mid; ++i)
	{
		int temp = data[i];
		data[i] = data[cnt - 1 - i];
		data[cnt - 1 - i] = temp;
	}
}

static void EndFlip()
{
	cout << '0' << endl;
}

static void FlipAdjust(vector<int>& data, size_t index)
{
	size_t cnt = data.size();
	size_t delta = (cnt - index) / 2;
	for (size_t i = index; i < (index + delta); ++i)
	{
		size_t swapIndex = cnt - 1 - i + index;
		int temp = data[i];
		data[i] = data[swapIndex];
		data[swapIndex] = temp;
	}
}

static void Flip(vector<int>& data, size_t startIndex)
{
	size_t cnt = data.size();

	if (startIndex >= (cnt - 1))
	{
		EndFlip();
		return;
	}

	int maxIndex = startIndex;
	int max = data[startIndex];
	for (size_t i = startIndex + 1; i < cnt; ++i)
	{
		if (data[i] > max)
		{
			maxIndex = i;
			max = data[i];
		}
	}

	if (maxIndex == startIndex) // The bottom one is already the biggest.
	{
		while((startIndex < cnt) && (data[startIndex] == max))
			++startIndex;
		Flip(data, startIndex);
		return;
	}

	if ((maxIndex != (cnt - 1)) && (data[cnt - 1] < max)) // The biggest one is not on the top
	{
		// Flip the stack from the biggest one.
		cout << (maxIndex + 1) << ' ';
		FlipAdjust(data, maxIndex);
	}

	// Now flip the stack completely because the biggest one is already on the top.
	cout << (startIndex + 1) << ' ';
	FlipAdjust(data, startIndex);

	// Now the bottom one is already the biggest, so flip the left ones.
	Flip(data, startIndex + 1);
	
	return;
}

static void OutputVec(const vector<int>& data)
{
	size_t cnt = data.size();
	for (int i = cnt - 1; i >= 0; --i)
	{
		cout << data[i];
		if (i > 0)
			cout << ' ';
	}
	cout << endl;
}

static void DoJob(char* line)
{
	vector<int> data;
	GetVecFromStr(data, line);
	OutputVec(data);
	Flip(data, 0);
}

#define MAX_BUF 4096

static void Test()
{
	char buf[MAX_BUF];
	while(fgets(buf, MAX_BUF, stdin))
	{
		if ((buf[0] == '\0') || (buf[0] == '\n'))
			return;
		DoJob(buf);
	}
}

int main(int argc, char* argv[])
{
	Test();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值