字典序全排序【permutation】+火车进出站

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

【解题思路】

首先:构造出所有可能的输出序列,

然后:用字典序输出

初始化一个sort vector<string>: 每种输出结果用string形式存入vector中,然后对vector进行sort,按照字典序排序。

#include <stack>
#include <iostream>
#include <stack>
#include <algorithm>
#include <vector>

using namespace std;

bool isOutNum(int *push, int *pop, int len)//判断pop是不是push的出栈序列
{
	if (push == NULL || pop == NULL || len <= 0)
		return false;
	stack<int> Stack;
	int i = 0, j = 0;
	for (i = 0;i<len;i++)//依次把push中的数入栈
	{
		Stack.push(push[i]);
		while (j<len && Stack.size() != 0 && pop[j] == Stack.top())//依次判断pop序列每个值是否与栈顶相等
		{
			Stack.pop();
			j++;
		}
	}
	return Stack.empty();
}

int main()
{
	int N;
	while (cin >> N)
	{
		//初始化数组
        int *pushNum = new int[N];
		int *popNum = new int[N];
     
		for (int i = 0;i<N;i++)
		{
			cin >> pushNum[i];
			popNum[i] = pushNum[i];
		}
        //pop 是有序的排列
		sort(popNum, popNum + N);// 这里因为是连续的指针区间 

		vector<int> vec(N);//初始化一个vector;
		for (size_t i = 0; i < vec.size(); i++)
		{
			vec[i] = popNum[i]; //将pop中的数值赋值到vec中要使用循环的
		}

		do
		{
			if (isOutNum(pushNum, popNum, N))//如果该排列正确,则输出
			{
				for (int i = 0;i<N - 1;i++)
					cout << popNum[i] << " ";
				cout << popNum[N - 1] << endl;
			}
		} while (next_permutation(popNum, popNum + N));//获取下一个排列       
	}
	return 0;
}
       

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值