zoukankan      html  css  js  c++  java
  • 1051 Pop Sequence

    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

    题意:

      按照给定的顺序依次进栈,栈顶元素出战的顺序随意。问一个给定的序列是不是出栈的序列。

    思路:

      模拟。根据给定的序列依次入栈,入栈的过程中,如果栈顶元素与所给序列查询的位置处元素相等,则出栈,查询位置向后移动一位。另外,容器的大小有限,如果入栈的过程中,容器中的元素超出所给容量的话,输出NO即可。

    Code:

     1 #include <bits/stdc++.h>
     2 
     3 using namespace std;
     4 
     5 int main() {
     6     int m, n, k;
     7     cin >> m >> n >> k;
     8 
     9     for (int i = 0; i < k; ++i) {
    10         vector<int> seq(n);
    11         for (int j = 0; j < n; ++j) cin >> seq[j];
    12         int cur = 0;
    13         stack<int> s;
    14         for (int j = 1; j <= n; ++j) {
    15             s.push(j);
    16             if (s.size() > m) break;
    17             while (!s.empty() && s.top() == seq[cur]) {
    18                 s.pop();
    19                 cur++;
    20             }
    21         }
    22         if (cur == n)
    23             cout << "YES" << endl;
    24         else
    25             cout << "NO" << endl;
    26     }
    27     return 0;
    28 }
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    《软件工艺》-初评
    UI设计心得(1)
    理想生活应该是...
    OpenPOP.NET+OpenSMTP.NET=?最强.NET开源邮件组件 Mail.NET!
    Outlook应用开发(3)之插件引擎
    最近发现的几个酷.net代码
    买了几本新书,推荐一下
    一个游标简单例子
    winform中捕获程序未处理的所有异常
    DataTable的Merge方法和添加datatable到dataset
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12851793.html
Copyright © 2011-2022 走看看