九度 1366 棧的壓入彈出序列

題目描述:

輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否爲該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章