题目大意:给出n,入栈顺序1..n,给出一系列出栈顺序,0结束,开始下一组输入,最后n=0输入结束。
Input
The last block consists of just one line containing 0.
Output
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;
}