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.
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.
For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.
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
YES
NO
NO
YES
NO
题目要求判断给出的数组是否符合出栈能形成的顺序。
所以我们肯定需要定义一个栈:
当给出数组当前的数字与栈顶的数字不相同且栈的大小符合题目要求时,就继续入栈;相同时出栈,空栈时出栈。最后判断数组里的所有数字是否都能被栈输出即可,判断代码如下:
- bool is_right(vector<int> a){
- stack<int> order;//栈每次使用过后要清空,所以干脆定义在这里
- int in_number[N];
- for(int i=0;i
//1-N的数字 - in_number[i]=i+1;
- }
- int index = 0;
- order.push(in_number[index++]);//先将第一个数字入栈
- int i=0;
- for(;i
size();){ - if(a[i]!=order.top()&&order.size()
//当不相同且栈容量够时入栈 - order.push(in_number[index]);
- index++;
- }
- else if(a[i] == order.top()){//相同时出栈,并继续向后判断
- i++;
- order.pop();
- }
- else{
- break;
- }
- if(order.empty()) order.push(in_number[index++]);//栈为空时入栈
- }
- if(i
size()) return false; - return true;
- }
1. 空栈的时候记得入栈,可以避免一进一出的情况下出错;
2. 每次使用完栈记得清空!!!!!
- #include
- using namespace std;
- int M;//栈的最大容量
- int N;//数组长度
- int K;//需要检查的数组数量
-
- bool is_right(vector<int> a){
- stack<int> order;//栈每次使用过后要清空,所以干脆定义在这里
- int in_number[N];
- for(int i=0;i
//1-N的数字 - in_number[i]=i+1;
- }
- int index = 0;
- order.push(in_number[index++]);//先将第一个数字入栈
- int i=0;
- for(;i
size();){ - if(a[i]!=order.top()&&order.size()
//当不相同且栈容量够时入栈 - order.push(in_number[index]);
- index++;
- }
- else if(a[i] == order.top()){//相同时出栈,并继续向后判断
- i++;
- order.pop();
- }
- else{
- break;
- }
- if(order.empty()) order.push(in_number[index++]);//栈为空时入栈
- }
- if(i
size()) return false; - return true;
- }
-
- int main(){
- cin>>M>>N>>K;
- vector<int> number[K];
- for(int i=0;i
- for(int j=0;j
- int t;
- cin>>t;
- number[i].push_back(t);
- }
- if(is_right(number[i])) cout<<"YES"<
- else cout<<"NO"<
- }
- return 0;
- }
-
相关阅读:
顺序编码器--OrdinalEncoder类
【如何学习CAN总线测试】——鲁棒性测试
Windows 11可使AMD芯片性能下降15%
【电商】电商后台设计—购物车
F. Conditional Mix(数论/dp)
浅谈基于LoRa技术下智能建筑能耗管理系统的分析与设计
c#事件(event)
RadiantQ jQuery甘特图,资源分配单元计算的支持
思迈特软件Smartbi完成C轮融资,推动国产BI加速进入智能化时代
基于FPGA的电磁超声脉冲压缩检测系统 论文+源文件
-
原文地址:https://blog.csdn.net/weixin_55202895/article/details/126562933