Data structure Exercise 02-linear structure 3. Pop Sequence (25)

Source: Internet
Author: User

Given a stack which can keep M numbers at the most. Push n numbers in the order of 1, 2, 3, ..., N and pop randomly. You were 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 are 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 the one test case. For each case, the first line contains 3 numbers (all no more than): M (the maximum capacity of the stack), N (The Le Ngth 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 is separated by a space.

Output Specification:

For each pop sequence, print on one line "YES" if it is indeed a possible pops sequence of the stack, or "NO" if not.

Sample Input:

5 7 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2

Sample Output:

Yesnonoyesno
#include <iostream>#include<stack>using namespacestd;intMain () {intM//Maximum capacity of the stack    intN//The length of push sequence    intK//The number of pop sequence to be checkedCIN >> M >> N >>K; intI, J; intinput, temp; BOOLFlag =true; Stack<int>STA;  for(i =0; i < K; i++) {Temp=1; Flag=true;  for(j =0; J < N; J + +) {cin>>input;  while(Sta.size () <= M &&flag) {                if(Sta.empty () | | sta.top ()! =input) {Sta.push (temp++); }                Else if(Sta.top () = =input)                    {Sta.pop ();  Break; }            }            if(Sta.size () >M) {flag=false; }        }        if(flag) cout<<"YES"<<Endl; Elsecout<<"NO"<<Endl;  while(!sta.empty ()) Sta.pop (); }    return 0;}

Data structure Exercise 02-linear structure 3. Pop Sequence (25)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.