1051. Pop Sequence (25)

来源:互联网 发布:巴西黑帮知乎 编辑:程序博客网 时间:2024/05/18 04:36
时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 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>using namespace std;class stack{private:int temp;int n[1000];public:int i;int top(){return n[i];}void pop(){n[i--] = 0;}void push(int k){n[++i] = k;}stack(){i = -1;for(int j=0;j<1000;j++)n[j] = 0;}};void run(int m,int n){int count=1,k=1;//count代表接下来要push的数,//k记录该组检测已经接受了几个输入int temp;stack ss;cin>>temp;while(1){if(ss.i==-1 || ss.top()!=temp){//栈空时或者与要pop的数不等时ss.push(count++);if(ss.i >= m || count>n+1)break;//超出栈的大小或者压栈的数已经大于最大值}else{ss.pop();if(k == n)break;cin>>temp;k++;}}while(k<n){k++;cin>>temp;}if(ss.i != -1)cout<<"NO"<<endl;elsecout<<"YES"<<endl;}int main(){int m,n,k;cin>>m>>n>>k;//m是栈的大小for(int i=1;i<=k;i++)run(m,n);return 0;}

0 0
原创粉丝点击