【描述】
给定一个正整数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);
}