02-线性结构4 Pop Sequence
来源:互联网 发布:touchslide.js 编辑:程序博客网 时间:2024/06/05 11:15
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 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2
Sample Output:
YESNONOYESNO
刚开始一直没想明白,后来参考了别人的代码才明白应该如何做//CheckStack类package popsequence;import java.util.Stack;public class CheckStack {static boolean checkStack(int a[],int b,int c){//b=n,c=mStack<Integer> stack =new Stack<Integer>();int idx=0;int num=1;int length=b;int stackSize=c;stack.push(0);while(idx!=length){while(stack.peek()<a[idx]&&idx!=length&&(stack.size()<=stackSize)){stack.push(num++);}if(stack.peek()==a[idx]){stack.pop();idx++;}else{return false;}}return true;}}main
package popsequence;import java.util.*;///判断是否为可能的出栈顺序public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);//int M,N,K;int M=in.nextInt();int N=in.nextInt();int K=in.nextInt();int[][] data =new int[K][N];for(int i=0;i<K;i++){for(int j=0;j<N;j++){data[i][j]=in.nextInt();}}boolean flag;for(int i=0;i<K;i++){flag=CheckStack.checkStack(data[i],N,M);if(flag){System.out.println("Yes");}else{System.out.println("No");}}}}总体思路为:
先push进去一个0,从而使得比较可以进行。
如果栈顶元素比第一个出栈元素要小,则入栈。
如果栈满,则比较出栈元素和栈顶元素,如果不等,错误;相等则出栈,重复这一步骤;
若在栈满之前相等,则pop,和下一个出栈元素比较,重复以上步骤。
顺便PTA的Java代码怎么传类文件啊?不是很清楚,都不知道怎么提交。
0 0
- [PTA]02-线性结构4 Pop Sequence
- 02-线性结构4 Pop Sequence
- [pta]02-线性结构4 Pop Sequence
- 02-线性结构4 Pop Sequence
- 02-线性结构4 Pop Sequence
- 02-线性结构4 Pop Sequence
- 02-线性结构4 Pop Sequence
- 线性结构4 Pop Sequence
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- PAT 02-线性结构4 Pop Sequence【JAVA实现】
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- 02-线性结构4 Pop Sequence (25分)
- 17.预防死锁
- 关于Java的File.separator
- php 裁剪为任意大小的图像,图像不变形
- js判断请求是http还是https
- C语言中数组的初始化问题
- 02-线性结构4 Pop Sequence
- 个人总结1-我的大学
- NMS——非极大值抑制
- Linux--网络编程(一)网络介绍
- Hibernate缓存机制之快照
- JQuery动画
- 第四周:[Leetcode]207. Course Schedule
- 浅谈各种拒绝服务攻击的原理与防御
- 支持对列表操作的栈(lua)