C 堆栈性质的运用 02-线性结构4 Pop Sequence (25分)

02-线性结构4 Pop Sequence (25分)

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.

Sample Input:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2

Sample Output:

YES
NO
NO
YES
NO

判断给定序列能否由堆栈顺序入栈,任意出栈得到
将1——N按顺序入栈
即一开始num=1,与给定序列的第一个数比较;
若给定序列的第i个数小于num,则能由堆栈得到,返回NO
若给定序列的第i个数大于num,则num++,直到num等于该数,此时出栈可得到该数,下一次入栈也是num+1;
size存放栈内元素个数,入栈则size+1,出栈则size-1;
注意点
列表模拟栈,空栈时栈头指针也要指向第一个,即下标0;
为了后面比较size是否爆栈,每次入栈需从0开始计数。

#include<stdio.h>
 
int main() 
{
	int N,M,K;
	int i,j,a[1000];
	scanf("%d %d %d",&M,&N,&K);
	for(i=0;i<K;i++){
		for(j=0;j<N;j++)scanf("%d",&a[j]);
		int stack[1000]={0},top=0;//top为栈顶下标
		int num=1;
		j=0,stack[0]=num;
		while(j<N){
			if(a[j]<stack[top])break;//比栈顶元素小 
			while(a[j]>stack[top]){  //需要继续压入数据 
				stack[++top]=++num;
			}
			if(top>=M)break;     //栈内个数大于栈容量,退出循环 
			if(a[j]==stack[top]){   //栈顶为列表元素——则出栈 
				top--;
			}
			if(top<0)stack[++top]=++num;  
			//若下标为负数,则指向下标0,
			j++;
		}
		if(j==N)printf("YES\n");
		else printf("NO\n"); 
	}
	return 0;
}

堆栈实现
用栈模拟
先把1入栈,不行再入栈2,直到与n匹配,
看栈的大小是否超过所需值 ;
符合则出队刚才的元素;

#include<stack>
#include<iostream>
using namespace std;

int main(){
	int m,n,k;
	cin>>m>>n>>k;
	while(k--)
	{
		bool flag=true;
		stack<int> S;
		int num=1;
		
		for(int i=0;i<n;i++){    //n个数字 
			int temp;
			cin>>temp;   //读入数字 
			if(flag){       //没有退出标志,进行判断 
				while(S.empty()||S.top()!=temp){  //栈为空或栈顶元素不为所给值 
					S.push(num++);   //将1开始的数字逐个入栈 
					if(S.size()>m) {
					flag=false; //退出标记 
					break;       //退出该循环 
					}
				}
				if(flag&&S.size()>=1&& S.top()==temp)   
				//没有退出标记,且S有元素,且头元素为需要pop的元素 
					S.pop();
				}
			}	
		//n个数字读完
		if(flag) cout<<"YES"<<endl;
		else cout<<"NO"<<endl; 
	}
}
发布了77 篇原创文章 · 获赞 3 · 访问量 3024

猜你喜欢

转载自blog.csdn.net/BLUEsang/article/details/105373408
今日推荐