zoukankan      html  css  js  c++  java
  • [九度][何海涛] 栈的压入压出

    题目描述:

    输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

    输入:

    每个测试案例包括3行:

    第一行为1个整数n(1<=n<=100000),表示序列的长度。

    第二行包含n个整数,表示栈的压入顺序。

    第三行包含n个整数,表示栈的弹出顺序。

    输出:

    对应每个测试案例,如果第二个序列是第一个序列的弹出序列输出Yes,否则输出No。

    样例输入:
    5
    1 2 3 4 5
    4 5 3 2 1
    5
    1 2 3 4 5
    4 3 5 1 2
    
    样例输出:
    Yes
    No

    用一个栈来模拟,可以做到O(n)
     1 #include <iostream>
     2 #include <stack>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     int a[100000];
     8     int b[100000];
     9     int n;
    10     stack<int> s;
    11 
    12     while(cin >> n)
    13     {
    14         for(int i = 0; i < n; i++)
    15             cin >> a[i];
    16 
    17         for(int i = 0; i < n; i++)
    18             cin >> b[i];
    19 
    20         bool flag = true;
    21         int index = 0;
    22         while(!s.empty())
    23             s.pop();
    24 
    25         for(int i = 0; i < n; i++)
    26         {
    27             if (!s.empty() && s.top() == b[i])
    28                 s.pop();
    29             else
    30             {
    31                 bool findIt = false;
    32                 while(index < n)
    33                 {
    34                     s.push(a[index]);
    35                     if (a[index] == b[i])
    36                     {
    37                         index++;
    38                         findIt = true;
    39                         break;
    40                     }
    41 
    42                     index++;
    43                 }
    44 
    45                 if (!findIt)
    46                 {
    47                     flag = false;
    48                     break;
    49                 }
    50                 else
    51                     s.pop();
    52             }
    53         }
    54 
    55         if (flag)
    56             cout << "Yes" << endl;
    57         else
    58             cout << "No" << endl;
    59     }
    60 }
  • 相关阅读:
    java_十进制数转换为二进制,八进制,十六进制数的算法
    vim常用命令 vim键盘布局
    百度HTTPS加密搜索有什么用?
    delete
    hadoop2的automatic HA+Federation+Yarn配置的教程
    MinGW GCC下sleep()函数问题
    delete
    8天学通MongoDB——第一天 基础入门
    8天学通MongoDB——第六天 分片技术
    8天学通MongoDB——第五天 主从复制
  • 原文地址:https://www.cnblogs.com/chkkch/p/2781427.html
Copyright © 2011-2022 走看看