您的位置:首页 > 产品设计 > UI/UE

1051. Pop Sequence (25)

2015-03-19 20:46 411 查看
时间限制

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 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

这里所用的接受输入的方法其实非常的不明智,也就是每次接受一个,而不是一组,这样带来的隐患就是每次检测完一组都必须考虑我的该组数据是不是已经接受完了?如果没有,还要在接受剩下的没用的数据。否则后果就是这次的输入没有接收完,带到了下一组,从而影响了下一组的结果。

比较靠谱的做法应该是在检查一组时一次性将所有的输入全部纳入,用的时候再一个个取,这样就不用担心上述的隐患了

#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;
else
cout<<"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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++