标签:
数组实现:
#include <stdio.h>
#define N 1000
int main()
{
int i, n, target[N];
while(scanf("%d", &n) == 1)
{
int stack[N], top = -1;
for(i = 0; i < n; i++) scanf("%d", &target[i]);
int A = 1, B = 0;
int ok = 1;
while(B < n)
{
if(A == target[B]) { A++; B++; }
else if(top >= 0 && stack[top] == target[B]) { top--; B++; }
else if(A <= n) { stack[++top] = A++; }
else { ok = 0; break; }
}
printf("%s\n", ok ? "Yes" : "No");
}
return 0;
}
STL实现:
#include <cstdio>
#include <stack>
#define N 1000
using namespace std;
int main()
{
int i, n, target[N];
while(scanf("%d", &n) == 1)
{
stack<int> s;
for(i = 0; i < n; i++) scanf("%d", &target[i]);
int A = 1, B = 0, 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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qq_28236309/article/details/47206593