5-3 Pop Sequence (25分)

5-3 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
 
  • 时间限制:400ms
  • 内存限制:64MB
  • 代码长度限制:16kB
  • 判题程序:系统默认
  • 作者:陈越
  • 单位:浙江大学

题目判定

http://pta.patest.cn/pta/test/16/exam/4/question/665

#include <cstdio>  
#include <sstream>  
#include <cstring>  
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>

using namespace std;

#define  N 1001

/*
M (the maximum capacity of the stack)
N (the length of push sequence)
*/
int m, n, kk;
int a[N];

int main()
{
    //freopen("in.txt", "r", stdin);
    scanf("%d%d%d", &m, &n, &kk);
    int i, j;
    while (kk--)
    {
        for (j = 0; j < n; j++)
        {
            scanf("%d", &a[j]);
        }
		if(a[0] > m) // 这里第一个元素就比栈容量还大 直接 NO 跳过
		{
			printf("NO\n");
			continue;
		}
		stack<int> sta ;
		int nextNum ;
		for(i = 1 ; i <= a[0]  ; i++)
		{
			sta.push(i) ;
		}
		int popNum = sta.top() ;
		sta.pop(); // 弹出第一个数
		nextNum = popNum + 1 ; // 下一个应该入栈的数

		bool flag = true ;
		for(i = 1 ; i < n ; i++)
		{
			int nowNum = a[i] ;
			if(nowNum < nextNum)
			{
				if(sta.empty())
				{
					flag = false ;
				}else{
					int staTop = sta.top() ;
					if(nowNum < staTop) // 小于栈顶元素 错误
					{
						flag = false ;
						break ;
					}else if(nowNum == staTop){ // 等于栈顶元素 直接弹出
						sta.pop() ;
					}
				}
				if(flag == false)
					break;
			}else{ // 大于等于下一个该入栈的元素
				int cnt = nowNum - nextNum + 1 ;
				int cnt2 = cnt + (int)sta.size() ;
				if(cnt2 > m) // 栈溢出 
				{
					flag = false ;
					break;
				}
				for(j = nextNum ; j <= nowNum ; j++)
				{
					sta.push(j) ;
				}
				sta.pop() ; // 弹出该元素
				nextNum = nowNum + 1; //下一个该入栈的元素 为此元素加上1 
			}
		}
		if(flag == false)
		{
			printf("NO\n") ;
		}else{
			printf("YES\n") ;
		}
	}
	return 0 ;
}


你可能感兴趣的:(5-3 Pop Sequence (25分))