UVA - 514 Rails(栈模拟)

题目:

给出一个序列,问将1,2,3,4……按从小到大的顺序入栈,能否得到给出的序列。

思路:

用stack模拟就可以了。

当前的cnt如果小于a[i],就将cnt入栈,否则就判断栈顶是不是和a[i]相等,如果相等则弹出,如果不相等,就不能获得给出的序列。

代码:

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define MAX 1000000000
#define mod 1000000007
#define FRE() freopen("in.txt","r",stdin)
#define FRO() freopen("out.txt","w",stdout)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int maxn = 1005;
int a[maxn],n;

int main(){
    //FRE();
    int a[maxn],n,x,kase=0;
    while(scanf("%d",&n) && n){
        stack<int> sta;
        while(scanf("%d",&x) && x){
            for(int i=0; i<n; i++){
                if(i==0){
                    a[i]=x;
                    continue;
                }
                scanf("%d",&a[i]);
            }
            int cnt=1,ok=0;
            for(int i=0; i<n; i++){
                bool flag = false;
                for(; cnt<a[i] && cnt<=n; cnt++){//开始写出了cnt!=a[i]导致一直WA
                    sta.push(cnt);
                    flag = true;
                }
                if(cnt==a[i]){
                    sta.push(cnt++);
                }
                if(!sta.empty() && sta.top()==a[i]){
                    sta.pop();
                }else{
                    ok=1;
                    break;
                }
            }
            if(ok){
                printf("No\n");
            }else{
                printf("Yes\n");
            }
        }
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/sykline/p/10446755.html