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()判断栈是否为空

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值