码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1022 Train Problem I 模拟栈题解

时间:2014-08-12 03:27:23      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:blog   使用   os   io   数据   for   2014   ar   

火车进站,模拟一个栈的操作,额外的栈操作,查看是否能按照规定顺序出栈。

数据量很少,故此题目很容易AC。

直接使用数组模拟就好。


#include <stdio.h>
const int MAX_N = 10;

char inOrder[MAX_N], outOrder[MAX_N], stk[MAX_N];
bool rs[MAX_N<<2];
int n;

int main()
{
	while (scanf("%d", &n) != EOF)
	{
		scanf("%s %s", inOrder, outOrder);

		int j = 0, out = 0, i = 0, st = 0;
		bool possible = true;
		while (possible && !(st == 0 && out == n))
		{
			for (; i < n && inOrder[i] != outOrder[out]; i++)
			{
				rs[j++] = true;
				stk[st++] = inOrder[i];
			}//push in
			i++;//Watch out: don't forget while inOrder[i]==outOrder[out]!
			rs[j++] = true;
			rs[j++] = false;
			out++;

			while (st > 0 && stk[st-1] == outOrder[out])
			{
				st--; out++;
				rs[j++] = false;
			}//pop back

			int k = 0;//check possible
			for (; k < st && stk[k] != outOrder[out]; k++);
			if (k < st) possible = false;
		}
		if (possible)
		{
			puts("Yes.");
			for (int i = 0; i < j; i++)
			{
				if (rs[i]) puts("in");
				else puts("out");
			}
		}
		else puts("No.");
		puts("FINISH");
	}
	return 0;
}

解法二:

#include <stdio.h>
const int MAX_N = 10;

char inOrder[MAX_N], outOrder[MAX_N], stk[MAX_N];
bool rs[MAX_N<<2];
int n;

int main()
{
	while (scanf("%d", &n) != EOF)
	{
		scanf("%s %s", inOrder, outOrder);

		int j = 0, out = 0, i = 0, st = 0;
		while (i<n && !(st == 0 && out == n))
		{
			for (; i < n && inOrder[i] != outOrder[out]; i++)
			{
				rs[j++] = true;
				stk[st++] = inOrder[i];
			}//push in
			i++;//Watch out: don't forget while inOrder[i]==outOrder[out]!
			rs[j++] = true;
			rs[j++] = false;
			out++;

			while (st > 0 && stk[st-1] == outOrder[out])
			{
				st--; out++;
				rs[j++] = false;
			}//pop back
		}
		if (st == 0 && out == n)
		{
			puts("Yes.");
			for (int i = 0; i < j; i++)
			{
				if (rs[i]) puts("in");
				else puts("out");
			}
		}
		else puts("No.");
		puts("FINISH");
	}
	return 0;
}



HDU 1022 Train Problem I 模拟栈题解,布布扣,bubuko.com

HDU 1022 Train Problem I 模拟栈题解

标签:blog   使用   os   io   数据   for   2014   ar   

原文地址:http://blog.csdn.net/kenden23/article/details/38504625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!