Stack and Queue Seven of the Data Structure Experiment of the Stack: Determination of the Popping Sequence

Data Structure Experiment of Stack and Queue 7: Determining the pop sequence
Time Limit: 30 ms Memory Limit: 1000 KiB
Submit Statistic Discuss
Problem Description
Give an initial stack sequence, the order of which is the stack sequence of elements, and the top element of the stack can be Pop the stack at any time, and each element can only be pushed into the stack in turn. Input a push sequence, followed by multiple sequences, please check whether these sequences are valid pop sequences for the given push sequence.
For example, the sequence 1, 2, 3, 4, 5 is the push sequence of a certain stack, the sequence 4, 5, 3, 2, 1 is a stack sequence corresponding to the push sequence, but 4, 3, 5, 1, 2 cannot be the pop sequence of the sequence. Assume that all numbers pushed onto the stack are not equal.
The first line of Input
inputs an integer n (1<=n<=10000), which represents the length of the sequence.
In the second line, n integers are entered, indicating the order in which the stack is pushed.
The third line enters the integer t (1<=t<=10).
Then enter t lines in turn, each line contains n integers, indicating each pop-up sequence to be judged.
Output
outputs one line for each test case. If the pop sequence can be obtained from the initial push sequence, output yes, otherwise output no.

Sample Input
5
1 2 3 4 5
2
4 5 3 2 1
4 3 5 1 2
Sample Output
yes
no
Hint

Source

#include<stdio.h>
#include<stdlib.h>
int a[10001],stacks[10001];
int main()
{
    int t,n,i;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    scanf("%d",&t);
    while(t--)
    {
        int temp,p=0,q=-1;
        for(i=0;i<n;i++)
        {
            scanf("%d",&temp);
            while(q==-1||stacks[q]!=temp)
            {
                if(p>=n)break;
                stacks[++q]=a[p++];
            }
            if(stacks[q]==temp)
                q--;
        }
        if(q==-1)
        {
            printf("yes\n");
        }
        else printf("no\n");
    }
    return 0;
}

THINk:
The idea is to first store these numbers in the array, then from 0 to n, enter temp for comparison, and push the stack from 0 to N in turn, until the top element of the stack is the same as temp, so this time the while loop statement is used , if these elements are all pushed into the stack and they are not the same, it is an illegal sequence. For example, the template sequence is 12345. For 45321, enter 4 first, and execute the while loop until 4 is found. To make 4 pop out of the stack, continue to input temp, continue to compare, if it is a legal sequence, the final value of p should be -1;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324673453&siteId=291194637