Train Problem

本文介绍了一种使用栈数据结构解决实际问题的方法,通过输入火车数量及进站、出站顺序,判断能否按照指定顺序完成操作,并输出对应的操作序列。此过程涉及栈的基本操作和逻辑判断。

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

题意很简单,输入n, str1, str2.

n为火车的个数,str1为火车进站的顺序,str2为火车出站的顺序。

若能满足条件,则输出火车进站出站的顺序,不能则输出No.


思路:

赤裸裸的栈的应用。。。由于以前就用栈写过括号匹配和表达式求值,所以虽然思路很清晰,但是就是写不出来代码。。。以后要多写。


代码如下:

#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<stack> #include<vector> #include<algorithm> using namespace std; int main() { int num, count; string str1, str2; stack<int> train; vector<string> out; while(scanf("%d", &num) != EOF) { cin>>str1>>str2; out.clear(); //初始化 while(!train.empty())//初始化 train.pop(); count = 0;//初始化 for(int i = 0; i < num; ++i) { train.push(str1[i]); //入栈一次就比较出站的顺序 out.push_back("in"); if(train.top() == str2[count]) //相同则出栈 { count++; train.pop(); out.push_back("out"); while(!train.empty() && train.top() == str2[count]) //真巧妙,没想出来。。。 { count++; train.pop(); out.push_back("out"); } } } if(train.empty()) //全部匹配 { printf("Yes.\n"); for(int i = 0; i <out.size(); ++i) cout<<out[i]<<endl; printf("FINISH\n"); } else { printf("No.\n"); printf("FINISH\n"); } } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值