題目的意思其實跟問原本順序是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;
}
}