题目大意:输入n(n=0时退出),表示有n个数,入栈序列默认为1,2,,,n,给出若干个个序列,问该序列是否是一个合法的出栈序列,若是输出Yes,否则输出No,输入为0时结束。
解题思路:直接用栈模拟,注意输出格式和字母大小写
AC代码:一种是我自己写的,另一种是参考紫书写的。
代码一:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define mc(a,b) memcpy(a,b,sizeof(b))
#define inf 0x3f3f3f
#define fin freopen("in.txt", "r", stdin)
#define fout freopen("out.txt", "w", stdout)
typedef long long ll;
typedef unsigned long long ULL;
const int mod=1e9+7;
const int N=1e5+7;
int n;
int a[N];
stack <int> s;
int main()
{
// fin;
while(scanf("%d",&n)&&n)
{
int x;
while(scanf("%d",&x)){
if(x==0) break;
int f=0;
while(!s.empty()){
s.pop();
}
int t=1;
while(x>t){
s.push(t++);
}
t=x+1;
for(int i=1;i<n;i++){
scanf("%d",&x);
if(x>=t){
while(x>t){
s.push(t++);
}
t=x+1;
}
else{
if(!s.empty()&&x==s.top()){
s.pop();
}
else f=1;
}
}
printf("%s\n",f?"No":"Yes");
}
printf("\n");
}
return 0;
}
代码二:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define io ios::sync_with_stdio(0),cin.tie(0)
#define ms(arr) memset(arr,0,sizeof(arr))
#define mc(a,b) memcpy(a,b,sizeof(b))
#define inf 0x3f3f3f
#define fin freopen("in.txt", "r", stdin)
#define fout freopen("out.txt", "w", stdout)
typedef long long ll;
typedef unsigned long long ULL;
const int mod=1e9+7;
const int N=1e5+7;
int n,target[1100];
int main()
{
// fin;
while(scanf("%d",&n)&&n!=0){
while(scanf("%d",&target[1])&&target[1]!=0){
stack <int> s;
for(int i=2;i<=n;i++) scanf("%d",&target[i]);
int a=1,b=1;
int 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");
}
printf("\n");
}
return 0;
}