#45722: c++只用stack處理


jiangzhu0518@gmail.com (吱嘎)

學校 : 臺北市立中山女子高級中學
編號 : 302154
來源 : [123.193.248.14]
最後登入時間 :
2025-04-17 22:27:11
c123. 00514 - Rails -- UVa514 | From: [123.193.248.14] | 發表日期 : 2025-04-05 19:30

題目的意思其實跟問原本順序是1順到5的一串數字進入stack後能否以某個順序出來是一樣的,就是要檢查是否遵循先進後出。

它的敘述是可以先進站等也可以直接開過去,進站等就是進入stack容器等待,直接開過去相當於放進去就立刻pop。

例如32451就是可以的(push 1,push 2,push 3,pop,pop,push 4,pop,push 5,pop,pop)

 

 

程式碼 :

#include <iostream>
#include <stack>
using namespace std;

void test(int N);

int main() {
    int N;
    while ( cin>>N && N!=0 ) {
        test(N);
    }
    return 0;
}

void test(int N) {
    while(true){
        stack<int> st;
        int arr[10000];
        int j=1;
    
        cin>>arr[1];
        if (arr[1] == 0) return; 
    
        for (int k = 2;k <= N;k++){
            cin>>arr[k];
        }
       
        for (int i = 1; i <= N; i++) {
            st.push(i);
        
          while (!st.empty() && st.top() == arr[j]) {
          st.pop();
          j++;
          }
        }
        cout << (st.empty() ? "Yes" : "No") << endl;
    }
}

 
ZeroJudge Forum