九度 1366 栈的压入弹出序列

来源:互联网 发布:数据库面试题及答案 编辑:程序博客网 时间:2024/04/28 18:57
题目描述:

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列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

#include <cstdlib>#include <cstdio>#include <stack>#include <vector>  using namespace std; bool isPopOrder(const vector<int> &push, const vector<int> &pop, int length){     bool sequence = false;           if(push.empty() || pop.empty() || length < 0)        return sequence;           vector<int>::const_iterator iNextPush = push.begin();     vector<int>::const_iterator iNextPop  = pop.begin();           stack<int> stack;           while(iNextPop - pop.begin() < length)     {         while(stack.empty() || stack.top() != *iNextPop)         {              if(iNextPush - push.begin() == length)                  break;                             stack.push(*iNextPush);              ++iNextPush;              }                   if(stack.top() != *iNextPop)              break;                   stack.pop();         ++iNextPop;     }           if(stack.empty() && iNextPop - pop.begin() == length)//这是if 不是while          sequence = true;               return sequence;} int main(int argc, char *argv[]){    int n;    while(scanf("%d", &n) != EOF)    {        int value;        vector<int> push, pop;                 int i;        for(i = 0; i < n; ++i)        {            scanf("%d", &value);            push.push_back(value);        }                 for(i = 0; i < n; ++i)        {            scanf("%d", &value);            pop.push_back(value);        }                 if(isPopOrder(push, pop, n))            printf("Yes\n");        else            printf("No\n");                      }              return 0;}


0 0
原创粉丝点击