HDU1022 Train Problem I

第一次周赛就有这道题,现在还耿耿于怀
主要就是用到栈,水题啦

#include <cstdio>
#include <stack>
#include <cstring>

using namespace std;

const int MAX = 1000 + 10;

int n;
char in[MAX], out[MAX];
int pro[2 * MAX];                   //记录火车进出过程,1进栈0出栈

int main()
{
    while (scanf("%d", &n) == 1)
    {
        scanf("%s%s", in, out);
        stack<char> s;              //记录栈内火车
        int a = 0, b = 0;           //a记录in的个数,b记录out的个数
        int step = 0;               //记录火车一共进行多少个动作,包括入栈出栈
        int ok = 1;
        while (b < n)               //out中火车节少于n
        {
            if (in[a] == out[b])    //如果进入的火车和出去的火车节一样,直接进栈出栈
            {
                a++;
                b++;
                pro[step++] = 1;
                pro[step++] = 0;
            }
            else if (!s.empty() && s.top() == out[b])
            {
                s.pop();
                b++;
                pro[step++] = 0;
            }
            else if (a < n)
            {
                s.push(in[a++]);
                pro[step++] = 1;
            }
            else
            {
                ok = 0;
                break;
            }
        }
        printf("%s.\n", ok ? "Yes" : "No");
        if (ok)
        {
            for (int i = 0; i < step; i++)
                printf("%s\n", pro[i] ? "in" : "out");
        }
        printf("FINISH\n");
    }
    return 0;
}

  

从这道题学到的一点操作
stack<> s;
s.pop()出栈,s.push()入栈,s.pop()取栈顶元素,s.empty()判断栈是否为空

 

posted @ 2015-03-11 18:55  我不吃饼干呀  阅读(147)  评论(0编辑  收藏  举报