天天看点

模拟栈的出入 HDOJ 1022 Train Problem I

题目传送门:

http://acm.hdu.edu.cn/showproblem.php?pid=1022

题目大意是给出一个入栈的序列,判断一个给出的序列是否可能是一个合法的出栈序列,若是,给出入栈和出栈的过程。

#include <iostream>
#include <cstring>

using namespace std;

int main(int argc, char const *argv[])
{
    int n,cntout,cntin,top,cnt; //标记当前信息
    int rec[]; //记录入栈出栈过程
    char stack[]; //栈
    char in[],out[]; //入栈出栈顺序
    while (cin >> n) {
        int flag = ; // 首先假定出栈顺序合法
        memset(stack,,sizeof(stack));
        top = cntout = cntin = cnt = ;
        cin >> in >> out;
        stack[top ++] = in[cntin ++];// 首元素入栈
        rec[cnt ++] = ;
        while (top > ) {
    // 当栈顶元素不是下一个要出栈元素且还有元素未入栈时入栈
            while (out[cntout] != stack[top - ] && cntin < n) {
                stack[top ++] = in[cntin ++];
                rec[cnt ++] = ;
            }
    /*当 全部元素都已入栈,栈顶元素仍不是下一个要出栈的元素,出栈顺序非法 */
            if (cntin == n && stack[top - ] != out[cntout]) {
                cout << "No." << endl << "FINISH" << endl;
                flag = ;
                break;
            }
    // 栈顶元素已经是下一个要出栈的元素,栈顶元素出栈
            top --;
            cntout ++;
            rec[cnt ++] = ;
    // 栈空但仍有元素未入栈,队首元素入栈
            if (top ==  && cntin < n) {
                stack[top ++] = in[cntin ++];
                rec[cnt ++] = ;
            }
        }
        if (flag) {
            cout << "Yes." << endl;
            for (int i = ; i < cnt; ++i)
            {
                if (rec[i]) {
                    cout << "in" << endl;
                } else {
                    cout << "out" << endl;
                }
            }
            cout << "FINISH" << endl;
        }
    }

    return ;
}
           

继续阅读