hdu 1022 Train Problem I 栈模拟

本文介绍了一个使用C++实现的模拟栈算法题目,通过具体的代码示例详细解释了如何利用栈来处理输入数据,并判断是否能通过一系列的入栈(out)和出栈(in)操作使得初始栈为空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

难度:2

算法:模拟一个栈

大家只要了解一下栈的实现就能很好的模拟出这道提

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int n , sta[100] , od[100] , cnt;
char c1[100] , c2[100];
bool check() {
    cnt = 0;
    int i = 0 , j = 0 , s = 0;
    while(j < n) {
        if(c1[i] == c2[j]) {
            od[cnt++] = 1;
            od[cnt++] = 0;
            i++; j++;
        }
        else if(s > 0 && sta[s-1] == c2[j]) {
            od[cnt++] = 0;
            s--;
            j++;
        }
        else if(i < n) {
            od[cnt++] = 1;
            sta[s++] = c1[i];
            i++;
        }
        else return false;
    }
    return true;
}
int main() {
    while(~scanf("%d%s%s" , &n , c1 , c2)) {
        if(!check()) {
            puts("No.");
            puts("FINISH");
        }
        else {
            puts("Yes.");
            for(int i=0;i<cnt;i++) {
                if(od[i] == 1) puts("in");
                else puts("out");
            }
            puts("FINISH");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值