UVA-120

模擬題。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;
const int maxn=1e2+6;
typedef long long ll;
int st[maxn], st_cp[maxn];	// st存煎餅,st_cp存放正確的煎餅順序
char str[maxn];	// str用於輸入
queue<int> ans;	// ans記錄正確的翻轉順序

int transfer(char str[])	// 將輸入的str轉爲整數存進st, st_cp
{
	int len = strlen(str), cnt = 0;
	str[len] = ' ';
	stack<char> stk;	// 藉助了棧,方便操作
	for(int i=0; i<=len; ++i)
	{
		if(str[i] == ' ')
		{
			if(!stk.empty())
			{
				int tmp = 1, num = 0;
				while(!stk.empty())
				{
					num += tmp * (stk.top() - '0');
					tmp *= 10;
					stk.pop();
				}
				st[cnt] = num;
				st_cp[cnt++] = num;
			}
		}
		else 
			stk.push(str[i]);
	}
	return cnt;
}

int get_pos(int l, int r, int tar)
{
	for(int i=l; i<=r; ++i)
		if(st[i] == tar)
			return i;
}

void _reverse(int pos, int cnt)
{
	stack<int> stk;
	for(int i=0; i<=pos; ++i)
		stk.push(st[i]);
	for(int i=0; i<=pos; ++i)
	{
		st[i] = stk.top();
		stk.pop();
	}
	ans.push(cnt-pos);
}

void reverse(int cur, int cnt)	// 逆轉st[0, cur]的子序列,cnt爲st的長度
{
	int pos = get_pos(0, cur, st_cp[cur]);
	if(pos)
		_reverse(pos, cnt);
	pos = cur;
	_reverse(pos, cnt);
}

int main()
{
	while(gets(str))
	{
		int cnt = transfer(str);
		sort(st_cp, st_cp+cnt);
		for(int i=0; i<cnt; ++i)	//記得先輸出整個煎餅序列,因爲這個WA了一次
		{
			printf("%d", st[i]);
			if(i+1 != cnt) 
				putchar(' ');
			else 
				putchar('\n');
		} 
		for(int i=cnt-1; i>=0; --i)
		{
			if(st[i] == st_cp[i])
				continue;
			reverse(i, cnt);
		}
		ans.push(0);
		while(!ans.empty())
		{
			int pos = ans.front();
			ans.pop();
			printf("%d", pos);
			if(!ans.empty())
				putchar(' ');
		}
		putchar('\n');
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章