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
思路:
模拟堆栈操作验证出栈顺序是否合法。先用数组储存出栈顺序,再进行堆栈操作。如果要出栈的元素大于要入栈的元素,则循环入栈,直到栈顶元素等于该元素,则将弹出栈顶。如果要出栈的元素等于栈顶元素,则直接弹栈。如果要出栈的元素小于栈顶元素,则认为序列不合法,因为入栈元素是从小到大递增的,小的元素被压在下面出不来。如果循环过程都正常且循环结束后栈为空,则认为该出栈顺序合法。
代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int m;
typedef struct node
{
int data;
node *next;
} Node, *Stack;
Stack createStack()
{
Stack stack = new Node;
stack->next = NULL;
stack->data = 0;
return stack;
}
int push(Stack stack, int data)
{
if (stack->data == m)
return 0;
Stack node = new Node;
node->data = data;
node->next = stack->next;
stack->next = node;
stack->data++;
return 1;
}
int pop(Stack stack)
{
int data;
Stack popNode = stack->next;
data = popNode->data;
stack->next = popNode->next;
delete popNode;
stack->data--;
return data;
}
int main()
{
int n, num, isTrue, top;
std::cin >> m >> n >> num;
int a[n];
for (int i = 0; i < num; ++i)
{
Stack stack = createStack();
isTrue = 1;
for (int j = 0; j < n; ++j)
{
std::cin >> a[j];
}
for (int j = 0, k = 1; j < n && isTrue; ++j)
{
while (k <= a[j])
{
if (push(stack, k++) == 0)
{
isTrue = 0;
break;
}
}
top = stack->next->data;
if (top == a[j])
pop(stack);
else
{
isTrue = 0;
break;
}
}
if (isTrue && stack->data == 0)
std::cout << "YES\n";
else
std::cout << "NO\n";
}
return 0;
}