大学的数据结构课程中,经常会遇到判断出栈顺序合理性的题目,为此,将算法竞赛入门经典中的代码在此做个整理。
第一种是数组的形式解答;第二种是使用STL的解答。
#include<cstdio>
const int MAXN = 1010;
int n, target[MAXN];
int main()
{
while(~scanf("%d", &n))
{
int stack[MAXN], top = 0;
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(top && stack[top] == target[b])
{
top--; b++;
}
else if(a <= n)
stack[++top] = a++;
else
{
ok = 0; break;
}
}
printf("%s\n", ok ? "Yes" :