zoukankan      html  css  js  c++  java
  • 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

    题目大意:给出一个栈的最大容量,依次向栈中压入1,2,3。。。;问给出的序列能否通过出栈实现
    思路:模拟压栈,出栈;每次输入一个值 就判断当前值和栈顶的值是否,相同如果相同就弹出,否则一直压栈直到栈顶与输入值相同,当已经满栈,栈顶还是不和输入值相等就可以判断该序列不能通过出栈得到;
    此外,当栈中只有一个值,且和输入值相同,弹出后栈为空,就需要压入一个值,否则下一次循环的比较会出错

     1 #include<iostream>
     2 #include<stack>
     3 using namespace std;
     4 int main(){
     5   int n, m, k, i, j;
     6   cin>>m>>n>>k;
     7   for(i=0; i<k; i++){
     8       bool flag=true;
     9       int cnt=2, temp;
    10       stack<int> s;
    11       s.push(1);
    12     for(j=0; j<n; j++){
    13           cin>>temp;
    14           if(s.top()==temp)s.pop();
    15           else{
    16               while(s.top()!=temp&&s.size()<m){s.push(cnt++);}
    17               if(s.top()==temp)s.pop();
    18               else flag=false;
    19           }
    20           if(s.empty())s.push(cnt++);
    21     }
    22     printf("%s
    ", flag?"YES":"NO");
    23   }
    24   return 0;
    25 }
     
     
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    linux sed
    linux vim
    linux 文本处理
    Xception: Deep Learning with Depthwise Separable Convolutions
    Residual Attention Network for Image Classification
    ResNeXt:Aggregated Residual Transformations for Deep Neural Networks
    Densely Connected Convolutional Networks
    Deep Pyramidal Residual Networks
    SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size
    Wide Residual Networks
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9153500.html
Copyright © 2011-2022 走看看