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
分析
本题要求给定大小为M的堆栈,入栈顺序为1、2、3……N,给出K个出栈序列,判断该序列是否正确,找规律分析如下:
- 利用直接的方法,想了好久没想到如何判断,不妨看看堆栈出栈的规律,利用排除的方法,判断是否正确。
- 不考虑堆栈大小,对于N=3时,出栈序列有5种,即为3!-1种,有一种312序列是不可以的,因为3最先出栈,说明12都已按顺序入栈,则只能有321的情况。可以排除原因是大数(3)之后,出现了乱序的情况(1、2),按照该思路可以写代码排除不正确的情况,如序列: 3 2 1 7 5 6 4
- 若考虑堆栈大小,则,大数不能出现在前几个位置,如N=7,M=5时,6和7为大数,6不能出现在第1位,7不能出现在1、2位,否则栈溢出,如以下两种情况:
7 6 5 4 3 2 1
1 7 6 5 4 3 2
代码如下:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int M = scan.nextInt();
int N = scan.nextInt();
int K = scan.nextInt();
int a[] = new int[N];
for(int i = 0; i < K; i++)
{
for(int j = 0; j < N; j++)
a[j] = scan.nextInt();
if(is_pop_sequence(a, N, M))
System.out.println("YES");
else
System.out.println("NO");
}
}
public static boolean is_pop_sequence(int a[],int N, int M)
{
for(int i = 0; i < N-M; i++){/*1~N-M的位置不能出现大数,否则栈溢出*/
if(a[i]-i-1 >= M)
{
return false;
}
}
int i = 0;
while(i < N) {/*大的数之后,不能出现乱序的*/
int num = a[i];
int j;
for(j = i +1; j < num && j < N; j++)
{
if(a[j] > a[j-1]&&a[j] < num)/*num为大数,出现乱序情况,即7之后出现5、6*/
{
return false;
}
else if(a[j] > a[j-1]&& a[j] > num) {/*找到比num更大的数,退出循环,重新更新Num*/
break;
}
}
i = j;
}
return true;
}
}