一个FLAG #24# 铁轨(Rails,UVa 514)

例题6-2 铁轨(Rails,UVa 514),题目见参考。

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

int main()
{
    int n, x;
    
    vector<int> pop_order; // 保存所要求的出栈序列 
    stack<int> s;
    
    while (true) {
        scanf("%d", &n); // 指定几个元素 
        if (n == 0) break;
        
        while (true) {
            scanf("%d", &x);
            if (x == 0) break;    
            
            // 用 vector 保存所要求的出栈序列 
            pop_order.clear();
            pop_order.push_back(x);            
            for (int i = 1; i != n; ++i) {
                scanf("%d", &x);
                pop_order.push_back(x);
            }
            
            // 模拟进出栈过程 
                        
            int cur = 0; // 指向当前待出栈的元素
            x = 0; // 保存当前待进栈的元素 
             
            bool flag = true;            
            while (!s.empty()) s.pop(); // 清空stack 
            for (int i = 0; i != 2 * n; ++i) {
                // 每次循环要么进栈要么出栈 
                // 如果两种操作都不能执行,说明出栈序列不可行 
                if (!s.empty() && s.top() == pop_order[cur]) {
                    s.pop();
                    cur++;
                } else if (x <= n) {
                    s.push(++x);
                } else {
                    flag = false;
                    break;
                }
            }            
            printf("%s\n", flag? "yes" : "no");                    
        }
    }
    
    return 0;
} 

 

参考

[1] https://blog.csdn.net/hdd871532887/article/details/50369831

[2] oj

 

posted @ 2020-05-07 21:09  xkfx  阅读(234)  评论(0编辑  收藏  举报