1. 程式人生 > >線性結構4 Pop Sequence

線性結構4 Pop Sequence

mat most size int pac algorithm put ecif spa

02-線性結構4 Pop Sequence(25 分)

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., Nand 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 #include<iostream>
 2 #include<stack>
 3
#include<vector> 4 #include<algorithm> 5 using namespace std; 6 int M,N,K; 7 int check(vector<int> &vi){ 8 int m=0,n=0,cap=M+1; 9 stack<int> sta; 10 sta.push(0); 11 while(n<N){ 12 while(sta.size()<cap&&vi[n]>sta.top()) 13 sta.push(++m); 14 if(sta.top()==vi[n++]) sta.pop(); 15 else return 0; 16 } 17 return 1; 18 } 19 int main() 20 { 21 cin>>M>>N>>K; 22 vector<int> vi(N,0); 23 for(int j=0;j<K;j++){ 24 for(int i=0;i<N;i++){ 25 int n; 26 cin>>n; 27 vi[i]=n;} 28 if(check(vi)) 29 cout<<"YES"<<endl; 30 else 31 cout<<"NO"<<endl; 32 vi.clear(); 33 } 34 return 0; 35 }
View Code


線性結構4 Pop Sequence