poj1363 Rails--栈基础应用

本文探讨了如何通过栈操作解决输入解析问题,包括输入格式分析、数据组织及验证过程,详细介绍了两种实现方法及其性能对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:给出n,入栈顺序1..n,给出一系列出栈顺序,0结束,开始下一组输入,最后n=0输入结束。

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.

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

题目分析:严格根据题目的输入来判断一组数据结束和所有输入结束。

然后是栈的运用,当前元素比判断的顺序小的入栈,==则出栈,如果最后栈内有元素,说明无法完成此顺序。输出no


程序1:手工栈,运行47ms,程序2 stl stack 125ms

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=1010;
int n,a[maxn];
bool check(){
int i=1,j=1,top;
int s[maxn]={0};
top=-1;
for(i=1;i<=n;i++){
if(i<=a[j])
s[++top]=i;
while(top>=0&&s[top]==a[j]){
   top--;
j++;
}
    }
return top==-1;
}

int main(){
freopen("in.txt","r",stdin);

while(true){
scanf("%d",&n);
if(!n)break;
bool b=true;
while(b){
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(a[i]==0){
b=false;
break;
}
}
if(a[1]){
  if(check())printf("Yes\n");
  else printf("No\n");
}
}
printf("\n");   
}
return 0;
}


程序2:用stl stack

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=1010;
int n,a[maxn];
bool check(){
int i=1,j=1;
stack <int> s;
for(i=1;i<=n;i++){
if(i<=a[j])
          s.push(i);
while(!s.empty()&&s.top()==a[j]){
s.pop();
j++;
}
    }
return s.empty();
}


int main(){
while(true){
scanf("%d",&n);
if(!n)break;
bool b=true;
while(b){
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(a[i]==0){
b=false;
break;
}
}
if(a[1]){
if(check())printf("Yes\n");
else printf("No\n");
}
}
printf("\n");   
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值