Summary > There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.
Explanation > The problem requires reordering items on a stack, specifically to determine if the reordering can be done in a single pass.
Input Sample
5
1 2 3 4 5
5
5 4 1 2 3
6
6 5 4 3 2 1
Ouput Sample
Yes
No
Yes
C++
C++ 的 STL 提供了包括栈在内等特殊的数据结构,可以很方便地调用。参考了刘汝佳老师的代码
rails.cpp
#include<cstdio>#include<stack>usingnamespace std;
constint MAXN =1000+10;
int n, target[MAXN];
intmain()
{
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++; }
elseif (!s.empty() && s.top() == target[B]) { s.pop(); B++; }
elseif (A <= n) s.push(A++);
else { ok =0; break; }
}
printf("%s\n", ok ?"Yes":"No");
}
return0;
}
Python
Python再翻译
Python内置的数据结构相当强大,可以轻松模拟栈
rails.py
while1:
n = input()
if n =="":
break n = int(n)
s = []
target = [0] + list(map(int, input().split()))
A, B, ok =1, 1, 1while B <= n:
if A == target[B]:
A +=1 B +=1elif len(s) !=0and s[-1] == target[B]:
s.pop(-1)
B +=1elif A <= n:
A +=1 s.append(A)
else:
ok =0breakif ok ==1:
print("Yes")
else:
print("No")