判断输入序列是否是合法的栈输出序列
问题描述:
已知自然数1,2,…,N(1≤N≤10000)依次入栈(即a<b当且仅当a先于b入栈),请设计算法判断输入序列C1,C2,…,CN是否为可能的出栈序列。
例如:N=5 时,3,4,2,1,5是一个可能的出栈序列,因为其可以按如下操作获得: push 1, push 2, push 3, pop, push 4, pop, pop, pop, push 5, pop 输入:可包含多个测试用例,每个测试用例的输入有两行: 第一行是要判断序列的长度(即元素个数)N,(1≤N≤10000);
第二行是以N个正整数表示的出栈序列,以空格隔开;
如果序列长度为0,则结束;输出: 先输出要判断的序列,然后输出判断结论,如给出的序列是可能的出栈序列,则输出"Yes!",否则输出"No!"。例如
样例输入1:
5
3 4 2 1 5
5
3 5 1 4 2
0
样例输出2:
3 4 2 1 5: Yes!
3 5 1 4 2: No!
样例输入2:
1
1
2
1 2
2
2 1
3
3 1 2
0
输出2:
1:Yes!
1 2:Yes!
2 1:Yes!
3 1 2:No!
第四次作业的实验版本。
#pragma GCC optimize(3,"Ofast","inline")
#pragma G++ optimize(3)
#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef queue<int> q_i;
typedef queue<string> q_s;
typedef queue<double> q_d;
typedef queue<ll> q_ll;
typedef queue<char> q_c;
typedef priority_queue<int> pq_i;
typedef priority_queue<string> pq_s;
typedef priority_queue<double> pq_d;
typedef priority_queue<ll> pq_ll;
typedef stack<int> s_i;
typedef stack<string> s_s;
typedef stack<double> s_d;
typedef stack<ll> s_ll;
typedef stack<char> s_c;
typedef map<ll,ll> m_ll_ll;
typedef map<int,ll> m_i_ll;
typedef map<int,int> m_i_i;
typedef map<string,ll> m_s_ll;
typedef map<char,int> m_c_i;
typedef map<char,ll> m_c_ll;
const ll INF=0x3f3f3f3f;
#define rep(i,l,r) for(ll i=l;i<=r;i++)
#define per(i,l,r) for(ll i=r;i>=l;i--)
#define eif else if
#define N 2000005
#define M 100005
#define mm(dp) memset(dp,0,sizeof(dp))
#define mm1(dp) memset(dp,-1,sizeof(dp))
#define mm2(dp) memset(dp,0x3f,sizeof(dp))
#define IT set<int>::iterator
#define fs(n) fixed<< setprecision(n)
const double e=2.71828182845;
const double pi = acos(-1.0);
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(1)
{
int n;
cin>>n;
if(n==0)
break;
int a[n+1];
cout<<" ";
rep(i,1,n)
{
cin>>a[i];
if(i==1)
cout<<a[1];
else
cout<<" "<<a[i];
}
cout<<":";
stack<int>st;
int u=1;
rep(i,1,n)
{
if(i==a[u])
{
u++;
while(!st.empty()&&u<=n)
{
int p=st.top();
if(p!=a[u])
{
break;
}
else
{
u++;
st.pop();
}
}
}
else
{
st.push(i);
}
}
int flag=0;
while(!st.empty())
{
int p=st.top();
st.pop();
if(p!=a[u])
{
flag=1;
break;
}
else
u++;
}
if(flag==0)
cout<<"Yes!"<<endl;
else
cout<<"No!"<<endl;
}
return 0;
}