선형 구조 4 Pop Sequence (25 분)

18201 단어 데이터 구조
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
Code
#include 
#include 
#include 
#define MAXSIZE 1000
#define ERROR -1

typedef int ElementType;
typedef int Position;
typedef struct SNode *Stack;
struct SNode{
    ElementType *Data;
    Position Top;
    int Size;
};

Stack InitStack(int Size);
bool IsFull(Stack PtrS);
bool IsEmpty(Stack PtrS);
bool Push(Stack PtrS,ElementType X);
ElementType Pop(Stack PtrS);
void ClearStack(Stack PtrS);
/*  :(              )
1.       checked        num ;
2.         ,         ,   1,2,3...       num[0];
        num[0],  “NO”;          
3. num[h]>num[h-1],     ,     ,  ,        ,
        num[0],  “NO”;
   num[h]
int main()
{
    int m,n,k;
    scanf("%d %d %d",&m,&n,&k);
    Stack S = InitStack(m);
    int num[n];
    for(int i=0;i<k;i++)
    {
        int cnt = 0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&num[i]);
        }

        while(cnt!=num[0])
        {
            if(!Push(S,++cnt))
            {
                printf("NO
"
); goto out; } // printf("S->Data[%d] = %d
",S->Top,S->Data[S->Top]);
} Pop(S); for(int h=1;h<n;h++) { if(num[h]>num[h-1]) { while(cnt!=num[h]) { if(!Push(S,++cnt)) { printf("NO
"
); goto out; } // printf("S->Data[%d] = %d
",S->Top,S->Data[S->Top]);
} Pop(S); }else { if(Pop(S)!=num[h]) { printf("NO
"
); goto out; } } } printf("YES
"
); out: ClearStack(S); continue; } return 0; } Stack InitStack(int Size) { Stack S = (Stack)malloc(sizeof(struct SNode)); S->Data = (ElementType *)malloc(Size*sizeof(ElementType)); S->Top = -1; S->Size = Size; return S; } bool IsFull(Stack PtrS) { return PtrS->Top == PtrS->Size-1; } bool IsEmpty(Stack PtrS) { return PtrS->Top == -1; } bool Push(Stack PtrS,ElementType X) { if(IsFull(PtrS)) { return false; }else { PtrS->Top++; PtrS->Data[PtrS->Top] = X; return true; } } ElementType Pop(Stack PtrS) { if(IsEmpty(PtrS)) { return ERROR; }else { return PtrS->Data[(PtrS->Top)--]; } } void ClearStack(Stack PtrS) { PtrS->Top = -1; }

좋은 웹페이지 즐겨찾기