poj1363-Rails

题目:

 

Sample Input

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0

Sample Output

Yes
No

Yes

 

思路不难,使用栈和队列模拟整个过程,队列存放序列,1-n依次入栈,只要栈顶的元素和队首的元素相等就弹出,否则继续入栈。到最后判断栈是否为空。

#include <iostream>
#include <cstdio>
#include <stack>
#include <queue>
#include <vector>
using namespace std;

bool is_valid(queue<int> q){//O(n)
    stack<int> s;
    int n = q.size();
    for(int i=0; i<n; i++){//一定不能写成q.size()
        s.push(i+1);
        while(!s.empty()&&s.top()==q.front()){
            s.pop();
            q.pop();
        }
    }
    if(s.empty()==true)
        return true;
    return false;
}

int main(){
    int n;
    cin>>n;
    int seq;

    while(n!=0){
        cin>>seq;
        while(seq!=0){
            queue<int> q;
            q.push(seq);
            for(int i=1; i<n; i++){
                cin>>seq;
                q.push(seq);
            }

            if(is_valid(q))
                cout<<"Yes"<<endl;
            else
                cout<<"No"<<endl;
            cin>>seq;
        }
        cout<<endl;
        cin>>n;

    }
}

 

posted @ 2020-04-08 22:57  BrookTaylor  阅读(161)  评论(0编辑  收藏  举报