1.练习代码

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	const int MAXN = 1000;
	int n, target[MAXN];

	while(scanf("%d", &n) == 1)
	{
		stack<int> s;
		int A=1, B=1;
		for(int i=1; i<=n; i++)
			scanf("%d", &target[i]);
		int ok=1;

		while(B<=n)
		{
			if(A == target[B]){A++; B++;}
			else if(!s.empty() && s.top()==target[B]){s.pop(); B++;}
			else if(A<=n) s.push(A++);
			else{ok = 0; break;}
		}
		printf("%s\n", ok ? "Yes":"No");
	}
	return 0;
}

2.关键点分析

2.1题目

【小练习】铁轨
某城市有一个火车站,铁轨铺设和数据结构栈类似,只能从一侧进站,另一侧出站。
顺序为1、2、3、…、n的列车从一侧驶来,需要判断提前设定的出站调度顺序是否可行,可行返回yes,不可行返回no

样例
输入
5
5 4 1 2 3
输出
no

样例
输入
5
5 4 3 2 1
输出
yes

2.2分析

可使用STL标准库中的栈结构处理,代码走读如下。

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	const int MAXN = 1000;
	int n, target[MAXN];

	while(scanf("%d", &n) == 1) //输入列车数量n
	{
		stack<int> s;
		int A=1, B=1;
		//给定出栈顺序
		for(int i=1; i<=n; i++)
			scanf("%d", &target[i]);
		int ok=1;

		while(B<=n)
		{
			if(A == target[B]){A++; B++;} //进的刚好是需要出战的,就不处理直接放走
			else if(!s.empty() && s.top()==target[B]){s.pop(); B++;} //栈顶元素为需要出栈元素,则弹出
			else if(A<=n) s.push(A++); //出栈之前的元素都顺序压入栈结构
			else{ok = 0; break;} //找不到符合要求的列车,则判断顺序不可行返回错误
		}
		printf("%s\n", ok ? "Yes":"No"); //给出结论
	}
	return 0;
}

2.3运行结果

【小练习】铁轨

相关文章: