02-线性结构4 Pop Sequence
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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C++ (g++)
思路:
定义一个结构体,包含栈顶元素的位置、数组、数组大小。
bool check(vector array,int m,int n)
检查是否能成功出栈
定义一个栈s,用cnt来计数。
s的大小设置为传入的堆栈容量m,栈顶元素置为-1。
开始遍历输入的序列:
栈满的话返回false
否则入栈
当栈顶元素等于队列的队尾值时,出栈,进行上一个队列元素的匹配。
如果遍历完序列 即cnt==n,匹配完所有元素,说明按照这些元素的顺序可以顺利出栈,返回true,否则返回false。
主函数中。输入栈的容量,队列的长度以及需要检查的组数。
然后输入各个队列元素,进行检查。
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define maxsize 1000
struct Node{
int Top;//记录堆栈顶元素的位置
int Array[maxsize];
int Size;
};
typedef struct Node* Stack;
bool check(vector<int> array,int m,int n)
//得知道堆栈有多大m,要判断的序列有多大n
{
Stack s;
s=new struct Node;
int cnt=0;
s->Size=m;
s->Top=-1;
for(int i=1;i<=n;i++)
{
if(s->Top+1==s->Size) return false;//栈满
else s->Array[++s->Top]=i;
while(s->Array[s->Top]==array[cnt])
{
s->Top--;//出栈
cnt++;//数组往后移
}
}
if(cnt==n) return true;
else return false;
}
int main()
{
int M,N,K;//M栈 N序列 K组数
cin>>M>>N>>K;
vector<int> Array;
int a;
for(int i=0;i<K;i++)
{
Array.clear();
for(int j=0;j<N;j++)
{
cin>>a;
Array.push_back(a);
}
if(check(Array,M,N)) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
相关文章
- 02-线性结构3 Reversing Linked List
- 基于统一结构生成的网安信息抽取研究
- mp3格式音频文件结构解析图_mp3文件结构
- 如何创建Python程序包,Python程序包结构详解(超级详细)
- Oracle中无主键的表结构实现(oracle无主键)
- 深入探究Oracle内存结构,了解数据库高效运行的关键。(oracle内存结构)
- 结构SQL Server数据库的层级结构及应用(sqlserver 层级)
- 结构Oracle中查看表结构的方法(oracle中怎样查看表)
- 妙用Redis链表结构,有效提升系统性能(redis链表结构)
- 使用Oracle SQool构建数据库结构的最佳实践(oracle sqool)
- 什么才是真正的去中心化?V神的结构、政治与逻辑三重含义解析
- jquery的ajax简单结构示例代码
- MySQL复制表结构和内容到另一张表中的SQL语句