//ac,一定注意flag是在每次中读要初始化!
//有一点问题
//我一开始的想法是可以另设置一个初始栈,如果当前的输入栈顶和其相同,就pop,并且把初始栈的位置上移,如果不同就压入
//有一个错误就是我没有考虑栈是指点长度的,不是无限任意的
//之前写的删了,这是学习了胡凡的之后,完全自己写的。
#include<cstdio>
#include<stack>
//#define LOCAL
using namespace std;//又忘记using namespace了!
stack<int> st;
int M,N,K;//m表示stack的最大容量,n表示每一个序列的长度,K表示有几组数据
bool flag; //应该在每一组数据开始输入之前设置true
int arr[1010];
int main(){
#ifdef LOCAL
freopen("A1051data.in","r",stdin);
freopen("A1051data.out","w",stdout);
#endif
scanf("%d%d%d",&M,&N,&K);
while(K--){//这里由于N不需要保存,边读入,边输出
for(int i=1;i<=N;i++){
scanf("%d",&arr[i]);
}
while(!st.empty()){
st.pop();
}
int current=1;
flag=true;
for(int j=1;j<=N;j++){
st.push(j);
if(st.size()>M){
flag=false;
break;
}
while(!st.empty()&&st.top()==arr[current]){//一定注意这里是while如果一直匹配就要一直弹出的
st.pop();//这个while循环里始终没有入栈,所以上面那个循环入栈是正确的
current++;
}
}
if(st.empty()&&flag==true){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}
晴天的原版本
//一定注意flag是在每次中读要初始化!
//本题尤其要注意,一定是先入栈,再出栈,本题有栈宽度限制。必须先入才有可能出,不入怎么出呢!入了之后再检查是否和目标序列的当前各相同,相同说明这个位置出栈
//栈序列匹配,火车出入站,都是这个模板。
//先开数组,存放目标序列。设置一个flag表示此行行不行。
//先压栈检查是否溢出。没有的话
//晴天的思路逻辑还是相当严谨的
#include<cstdio>
#include<stack>
#define LOCAL
using namespace std;
const int maxn=1010;
int arr[maxn];//保存题目给定的出栈序列
stack<int> st;//定义栈st,里面存放int型元素
int main(){
#ifdef LOCAL
freopen("A1051data.in","r",stdin);
freopen("A1051data.out","w",stdout);
#endif
int m,n,k;
scanf("%d%d%d",&m,&n,&k);
while(k--){//k并不需要在后面用到,本题是边读入边输出,所以不需保存,所以用K--
while(!st.empty()){
st.pop();//如果栈不空,必须要清空栈
}
for(int i=0;i<n;i++){//把需要检查的序列读入到数组
scanf("%d",&arr[i]);
}
int current=1;//指向出栈序列中的待出栈元素
flag=true;
bool flag=true; //每一行都要提前置flag为true
for(int i=1;i<=n;i++){
st.push(i);//把i压入栈
if(st.size()>m){//如果这时超出了最大长度,则序列非法。这里不太懂
flag=false;
break;
}
//注意这里是while,栈顶元素与出栈序列当前的位置相同时。
while(!st.empty()&&st.top()==arr[current]){//此时栈有可能非空
st.pop();//反复弹栈并令current++
current++;
}
}
if(st.empty()==true&&flag==true){
printf("YES\n");
}
else{
printf("NO\n");//如果栈不为空,比如所有数都入栈一个也没有出,那就也是不行的
}
}
return 0;
}火车出入站延展思考
//火车出入站,根据晴神的思路的写法。晴神的写法就是简洁!!
#include<cstdio>
#include<stack>
using namespace std;
const int maxn=1010;
int arr[maxn];
stack<int> st;
int main(){
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&arr[i]);
}
while(!st.empty()){
st.pop();
}
int current=1;
for(i=1;i<=n;i++){//这种写法对于6 Enter 6 5 4 3 2 1也是可以的!
st.push(i);
while(!st.empty()&&st.top()==arr[current]){
st.pop();
current++;
}
}
if(!st.empty()) printf("NO\n");
else printf("YES\n");
return 0;
}
本文详细解析了PAT(A1051) Pop Sequence问题,通过C++实现,利用栈的数据结构解决该算法题目,探讨了如何进行有效的序列恢复操作。
1484

被折叠的 条评论
为什么被折叠?



