1051 Pop Sequence (25分)
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
這題蠻有意思的,數據結構考試就經常考這類,沒想到這次需要算法實現
仔細想了想還是直接模擬實現最簡單了
大概過程如下:
如果第一個要求輸出元素是5我們就需要把12345都壓到棧裏面,再pop出來5,第二個要求輸出的元素要麼是沒入棧的元素並且這個元素入棧後棧的大小還需要不超過給定的一個數字否則錯誤,要麼是棧裏面的元素,棧裏面的元素必須是棧頂元素,非棧頂元素就是錯誤的
#include <iostream>
#include <algorithm>
using namespace std;
#include <unordered_map>
#include <queue>
#include <stack>
int main()
{
//int sn[100][100]={0};
int maxStack,num,inNum;
cin>>maxStack>>num>>inNum;
for(int p=0; p<inNum; p++)//一共需要判斷inNum次
{
int sn[num];//用數列sn記錄需要輸出的元素
for(int i=0; i<num; i++)
{
cin>>sn[i];
}
//生成輸入隊列 1 到7,因爲棧的輸入順序是1-7,用隊列更方便點得到需要輸入的元素
queue<int> que;
for(int i=1; i<=num; i++)
que.push(i);
//判斷數組,用來判斷哪些元素在棧裏面,1即爲在棧內
int inStack[num+1]= {0};
int sign=1;
//判斷是否符合了規則
stack<int> sta;
for(int i=0; i<num&&sign; i++)
//這個sign就是如果已經有元素位置不對了,就沒必要再判斷後面的元素了
{
if(sta.size()==0||inStack[sn[i]]==0)
//棧爲空或者棧裏面沒有我們需要輸出的元素
{
while(que.front()!=sn[i])//一直輸出元素,知道得到了我們需要壓棧的元素
//比如7 我們就需要壓入1 2 3 4 5 6
{
sta.push(que.front());
//判斷是否越界
if(sta.size()>maxStack)
{
sign=0;
break;
}
//標記棧中存在了壓入的元素
inStack[que.front()]=1;
que.pop();
}
if(sign)//這是把7 再壓入棧,爲了方便判斷是否超過棧的最大容量了
{
sta.push(que.front());
inStack[que.front()]=1;
que.pop();
//判斷是否越界
if(sta.size()>maxStack)
{
sign=0;
break;
}
sta.pop();
}
}
else if(sn[i]==sta.top())//元素在棧頂
{
sta.pop();
continue;
}
else//元素不在棧頂,肯定就是不行的
{
sign=0;
break;
}
}
if(sign==1)
cout<<"YES";
else
cout<<"NO";
cout<<endl;
}
return 0;
}