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
起初认为可能能找到一个判定栈输出的数学方法,可惜数学不够牛逼,琢磨了一天没能解决。只得创建栈来模拟整个过程以判定。
1. 一旦出栈顺序给出,入栈顺序也就确定了。
5. 如果一个大数先出然后一个小数再出,那么这个大数出栈之后的下一个动作必然是POP,返回值必然是这个小数,否则NO。
2. 首先按数字大小顺序依次将小于第一个出栈元素的元素入栈,然后判定是否超过M。
3. 每次入栈,入栈元素必然是上次入栈元素加1,判定是否超过M。
open source:
#include <stdio.h>
#include <malloc.h>
typedef int ElementType;
struct LinkStack
{
ElementType data;
LinkStack* next;
};
LinkStack *CreateStack()
{
LinkStack *s;
s = (LinkStack*) malloc(sizeof(LinkStack ));
s->next = NULL;
return s;
}
bool IsEmpty( LinkStack *s )
{
return ( s->next == NULL );
}
int Length(LinkStack* s)
{
int i = -1;
LinkStack* temp = s;
while (temp)
{
i++;
temp = temp->next;
}
return i;
}
void Push(ElementType item, LinkStack* s)
{
LinkStack* newNode = (LinkStack*) malloc(sizeof(LinkStack));
newNode->data = item;
newNode->next = s->next;
s->next = newNode;
//printf("Pushed %d\n", item);
}
ElementType Pop(LinkStack* s)
{
if (s->next == NULL)
{
printf("Stack is empty.");
return NULL;
}
LinkStack* temp = s->next;
s->next = temp->next;
ElementType k = temp->data;
free(temp);
//printf("Pop %d.\n", k);
return k;
}
int main()
{
int M = 0;
int N = 0;
int K = 0;
scanf("%d %d %d", &M, &N, &K);
int* input = (int*) malloc(sizeof(int) * N);
int* result = (int*) malloc(sizeof(int) * K);
int index = K - 1;
while (K)
{
K--;
result[K] = 1;
int tempN = N;
while(tempN)
{
scanf("%d", &(input[N - tempN]));
tempN--;
}
LinkStack* stack = CreateStack();
int iterator = 0;
while (iterator < input[0])
{
Push(++iterator, stack);
}
if (Length(stack) > M)
{
result[K] = 0;
continue;
}
Pop(stack);
for (int i = 1; i < N; i++)
{
if (input[i] > input[i - 1])
{
while (iterator < input[i])
{
Push(++iterator, stack);
if (Length(stack) > M)
{
result[K] = 0;
break;
}
}
if (result[K] == 0)
{
break;
}
Pop(stack);
}
else if (input[i] < input[i - 1])
{
int out = Pop(stack);
if (out != input[i])
{
result[K] = 0;
break;
}
}
else
{
result[K] = 0;
break;
}
}
}
for (; index >= 0; index--)
{
if (result[index] == 0)
{
printf("NO\n");
}
else
{
printf("YES\n");
}
}
return 0;
}