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<stdio.h>
#include<stdlib.h>
struct LNode1 {
int Array[1010];
};
struct LNode {
LNode1 Data[1010];
int Last;
};
typedef LNode*List;
int FindFirst(int A[], int Data, int N) {
int i;
for (i = 0; i <= N - 1; i++)
{
if (A[i] == Data) break;
}
i++;
for (i; i <= N - 1; i++)
{
if (A[i] < Data)return A[i];
}
return 0;
}
bool JudgeArrar(int A[], int N, int StackSize)//有N个元素的数组A,判断是否顺序排列<1>
{
int i;
int max;
int tmp_max = 0;
for (i = 0; i <= N - 1; i++)
{
if (A[i] > i + StackSize)return false;
int j;
max = A[i];
if (FindFirst(A, A[i], N))
tmp_max = FindFirst(A, A[i], N);
else continue;
for (j = i + 1; j <= N - 1; j++)
{
if (A[j] < max)
{
if (A[j] > tmp_max)return false;
else { tmp_max = A[j];}
}
}
}
return true;
}
int main()
{
int i;
int StackMax, N, K;
int max, j;
List L = (List)malloc(sizeof(LNode));
L->Last = -1;
scanf("%d %d %d", &StackMax, &N, &K);
for (i = 0; i <= K - 1; i++)
{
for (int j = 0; j <= N - 1; j++)
{
scanf("%d", &L->Data[i].Array[j]);
}
L->Last++;
}//读入数据结束!
for (i = 0; i <= L->Last; i++)
{
if (JudgeArrar(L->Data[i].Array, N, StackMax))printf("YES\n");
else printf("NO\n");
}
return 0;
}
将输入按顺序保存,所有满足输出条件的序列,一定是从第一个元素开始遍历整个输出序列,如果发现元素x后面比x小的所有元素不是按从大到小的顺序排列,输出No,否则判断该点是否是可取值(比如第一个元素无法取得大于5的元素),符合则输出YES