火车进出站-字典序输出(华为OJ)
来源:互联网 发布:mac无线键盘出现乱键 编辑:程序博客网 时间:2024/04/29 23:11
【描述】
给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号。要求以字典序排序输出火车出站的序列号。
【输入】
有多组测试用例,每一组第一行输入一个正整数N(0<N<10),第二行包括N个正整数,范围为1到9。
【输出】
输出以字典序排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。
样例输入 3 1 2 3
样例输出
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
这是华为OJ上的一道题,可以拆分成两步,首先是构造出所有可能的输出序列,这在之前的博客已经给出–>点here。
不过还要求字典序输出,字典序是什么可百度之,这里我直接用sort vector< string>来解决。具体的说:每种输出结果以string形式存入vector中,然后对这个vector进行sort–》按照字典序排序。(除此之外,也可以自己写一个函数,在添加进vector之前,首先判定string的插入位置,也可以实现字典序排序。)
#include <iostream>#include <vector>#include<string>#include <algorithm>#include<math.h>using namespace std;vector<string> Solution;// 存放所有可能输出void f(string,string,string);void addSolution(string);int main(){ int N; cin>>N; string s,cur,in="",out=""; for(int i=1;i<=N;i++){cin>>cur;s+=cur;} //stack<char> stk; f(s,in,out); sort(Solution.begin(),Solution.end()); for(int i=0;i<Solution.size();i++){ for(int j=0;j<Solution[i].size()-1;j++){ cout<<Solution[i][j]<<" "; } cout<<Solution[i][Solution[i].size()-1]<<endl; } system("pause"); return 0;}void f(string remain,string in,string out){ if(remain.length()==0){// 没有等待的车厢了 //cout<<out+in<<endl; addSolution(out+in);//注意顺序是out+in } else{//有等待的车厢 if(in.length()==0){//如果站内没有车厢,新车厢直接进来,不用考虑先开走站内多少车 f(remain.substr(1,remain.length()-1),in+remain[0],out); } else{// 如果站内有车,那么将会根据新车厢开进来之前,驶出几辆站内的车分为多种情况。 for(int i=0;i<=in.length();i++){ //先开出停泊的共i节车厢,在开进来新车厢,注意这里用in模拟stack(每次往in字符串的头部添加新车厢编号)。 f(remain.substr(1,remain.length()-1),remain[0]+in.substr(i,in.length()-i),out+in.substr(0,i)); } } }}void addSolution(string s){ Solution.push_back(s);}
0 0
- 火车进出站-字典序输出(华为OJ)
- 火车进站问题(华为OJ)
- 火车进站 华为oj
- 火车进站-华为OJ
- 华为OJ火车进站
- 火车进出站问题---栈
- 全排列、判断栈序、火车进出站
- 华为oj之火车出站
- 【华为OJ】【072-火车进站】
- 【栈】华为OJ:火车进站
- 火车进站 华为oj(转)
- HDU 1022 火车进出站问题
- HDU1022--火车进出站问题Ⅰ
- HDU 1022 火车进出站问题
- 火车进出站序列问题简述
- HDU-1022-火车进出站问题 .
- hdoj 1022 火车进出站问题
- HDU 1022 火车进出站问题
- Hololens入门之语音识别(语音命令)
- Could not load the Tomcat server configuration at \Servers\Tomcat v7.0 Server at localhost-config
- 《算法学习与数据结构》part3 算法分析与数据结构之数组和广义表
- OC中类变量的@protected,@private,@public,@package区别
- Hadoop深入学习:HDFS主要流程——SNN合并fsimage和编辑日志
- 火车进出站-字典序输出(华为OJ)
- 染色法
- 【剑指offer】数值的整数次方-Java
- 去掉字符串中的所有空格
- 260. Single Number III
- ACGallery I: Sequence diagram for reading photos:
- 高度自动化(一)-发布可靠软件的系统方法一书
- android okhttp 使用方法
- android之隐藏状态栏,全屏显示和隐藏虚拟按键