Rails
Input
The input consists of blocks of lines. Each block except the last describes one train and possibly more requirements for its reorganization. In the first line of the block there is the integer N described above. In each of the next lines of the block there is a permutation of 1, 2, ..., N. The last line of the block contains just 0.
The last block consists of just one line containing 0.
The last block consists of just one line containing 0.
Output
The output contains the lines corresponding to the lines with permutations in the input. A line of the output contains Yes if it is possible to marshal the coaches in the order required on the corresponding line of the input. Otherwise it contains No. In addition, there is one empty line after the lines corresponding to one block of the input. There is no line in the output corresponding to the last ``null'' block of the input.
Sample Input
5 1 2 3 4 5 5 4 1 2 3 0 6 6 5 4 3 2 1 0 0
Sample Output
Yes No Yes
这道题是判断出栈顺序是否合法。。。
代码如下:
#include<cstdio>
#include<stack>
#include<cstring>
#include<cstdlib>
using namespace std;
int main()
{
int i,n;
int m,flag;
while(scanf("%d",&n),n)
{
flag=0;
while(!flag)
{
stack <int> s;//把对栈S的定义放在循环外面,可减去每次的输出都要复原的麻烦。
int t=1;
s.push(t);//把t=1作为栈顶元素插入
for(i=1;i<=n;i++)//输入待判断的出栈顺序
{
scanf("%d",&m);
if(m==0)//当输入的出栈顺序为‘0’时,表示对出栈顺序的输入结束//
{
flag=1;
break;
}
if(s.empty())//如果栈为空,就入栈,
{
t++;
s.push(t);
}
int top=s.top();
while(top!=m)//当栈顶元素与输出元素不相同时,比出栈的值小的数就入栈,直到栈顶元素与出栈的值相同。
{
if(t==n)
break;
t++;
s.push(t);
top=s.top();//更新栈顶元素
}
if(top==m)//当栈顶元素与出栈元素相同时,删除S的栈顶元素。
s.pop();
}
if(flag)//如果输入为‘0’,表示全部输入结束
break;
if(s.empty())//如果栈为空,说明每次删除的栈顶元素与输入的出栈顺序相同,即‘Yes’,否则‘No’。
puts("Yes");
else
puts("No");
}
printf("\n");
}
getchar(); //
return 0;
}
栈是限定只能在表的栈顶进行插入和删除操作的线性表。。。
栈的修改原则后进先出。。。