博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构上机 经典进出栈问题
阅读量:7257 次
发布时间:2019-06-29

本文共 1492 字,大约阅读时间需要 4 分钟。

 TonyY 等火车无聊的时候,会去观察火车的排列,有一天他思考这么一个问题,火车总站的火车只能进站,要出站的话只能先出最后进站的那辆车,那么知道火车的进站顺序,能不能把它的出站顺序调整成火车站想要的呢?

输入第一行为一个正整数 n 表示火车辆数(编号 1-n)(1<=n<=9)。然后为两个长度为 n 的序列,表示火车的进站顺序和出站顺序。每辆火车刚好进出站各一次。

如果可以调整,输出 Yes 和出入站顺序。如果不能,输出 No。

输入示例

3123321

输出示例

Yesinininoutoutout

代码:

#include 
#include
#include
#include
#include
#include
using namespace std;int itrain[100];int otrain[100];int order[100];int isright(int n){ bool flag = true; int i, j; int iturn = 1; int oturn = 1; stack
s; int cnt = 1; while(oturn <= n || !s.empty()) { if(itrain[iturn] == otrain[oturn]) { oturn++; iturn++; order[cnt++] = 2; if(oturn > n) break; continue; } else if(!s.empty()) { if(s.top() == otrain[oturn]) { order[cnt++] = 0; s.pop(); oturn++; if(oturn > n)break; continue; } else { if(iturn == n) { flag = false; break; } s.push(itrain[iturn]); iturn++; order[cnt++] = 1; } } else if(s.empty()) { s.push(itrain[iturn++]); order[cnt++] = 1; continue; } } if(!flag)return -1; else return cnt-1;}void Print(int n){ int i; for(i = 1; i <= n; i++) { if(order[i] == 2) { printf("in\nout\n"); } else if(order[i] == 1) { printf("in\n"); } else if(order[i] == 0) { printf("out\n"); } } }int main(){ int n, i; cin >> n; getchar(); char c; for(i = 1; i <= n; i++) { cin >> c; itrain[i] = c - '0'; } getchar(); for(i = 1; i <= n; i++) { cin >> c; otrain[i] = c - '0'; } int t = isright(n); if(t != -1) { printf("Yes\n"); Print(t); } else printf("No\n"); return 0;}

转载地址:http://pqpdm.baihongyu.com/

你可能感兴趣的文章
NoSQL -- php应用redis、mongodb
查看>>
Nginx 配置全解析(一)
查看>>
java中的URLEncoder和URLDecoder类的联系与区别
查看>>
我的友情链接
查看>>
Redis 连接池配置及redis操作
查看>>
MDT2012/13功能测试(1)—向MDT工作台添加资源
查看>>
NFS文件系统
查看>>
ExtJs的tab
查看>>
mysql安装
查看>>
pip笔记(译)
查看>>
python基础(七)——网络编程
查看>>
算法——二分搜索
查看>>
Ruby Code Style
查看>>
CSS3深度学习
查看>>
将rm删除的文件,放到回收站
查看>>
JSTL安装与使用
查看>>
winSocket编程(十)完成端口
查看>>
POJ 1026 Cipher[置换]
查看>>
[链接]--Microsoft Dynamics CRM 2011 Web Resource简介
查看>>
织梦标签
查看>>