• 欢迎访问废江网站,承蒙遇见 QQ群
  • 本站将致力于推送优质的java知识以及算法,开源代码!

02-线性结构4 Pop Sequence

浙大mooc 站点默认 5年前 (2019-10-11) 1344次浏览 已收录 1个评论 扫描二维码

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


题目的意思是,给我们一个固定的栈容量大小的栈(m表示栈容量),进栈n个数,最后给我们k组出栈序列,让我们判断是否是正确的出栈序列。
我想到了三种办法,最后只要一种成功了。
一开始,我想着找出某种规律,然后用改规律一组一组判断出栈序列的正确性,但是很遗憾失败了。
之后,我觉得给定n个数进栈,我把所有的出栈序列全部存到n个数组中,但是求出所有正确的出栈序列过于复杂,我没去尝试。
最好的办法就是模拟。

我们声明一个栈,用来模拟,把要测试的出栈序列放入数组中,然后for循环1-n一直进栈,然后进栈取栈顶元素和数组里的元素对比,一样则出栈,最后判断栈是否为空,空的话就说明是正确的出栈序列。这里我是用我写的栈函数来写的。。。。。。主函数代码几乎每段都写了注释


废江博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:02-线性结构4 Pop Sequence
喜欢 (2)
[]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址