TOJ-3072 Train Order

Time Limit: 1.0 Seconds    Memory Limit: 65536K
Total Runs: 313    Accepted Runs: 160



There is a railway station in PopPush City (See the picture below). All the trains arriving from A are numbered 1,2,3,... N. The station is dead-end, and some trains may stop here temporarily to let the behind trains pass by. Please note the trains cannot go backward, that is, once they enter the station, they cannot return to the direction A, and once they left the station to direction B, they cannot return the station too.

Now your task is, given N, output all the possible sequence when all the trains left the station. Each sequence should be represented as a string containing only 1,2,3...N. And the string should be sorted lexicographically.

Input

The first line is an integer T, the number of test cases. Then Tcases follows.

Each case contains only one number N in one line. You can assume 1 ≤ N≤ 9.

Output

Output all the possible sequences for each test case. Each line contains one sequence.

Sample Input

2
2
3

Sample Output

12
21
123
132
213
231
321

/*
   功能Function Description:     枚举全排列(STL函数)+栈的应用 TOJ-3072
   开发环境Environment:          DEV C++ 4.9.9.1
   技术特点Technique:
   版本Version:
   作者Author:                   可笑痴狂
   日期Date:                 	 20120801
   备注Notes:
		生成全排列的函数next_permutation(a,a+n)		
   题目来源:
		http://acm.tju.edu.cn/toj/showp3072.html					
*/

#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;

void init(int *a,int n)
{
	for(int i=0;i<n;++i)
		a[i]=i+1;
}


bool judge(int *a,int n)  //判断是否能按照a中的序列出站
{
	stack<int> s;
	int k=0;
	for(int i=1;i<=n;++i)
	{
		s.push(i);
		if(i==a[k])
		{
			while(!s.empty()&&s.top()==a[k])
			{
				s.pop();
				++k;
			}
		}
	}
	if(s.empty())
		return true;
	return false;
}

int main()
{
	int T,n,i;
	int a[11];
	cin>>T;
	while(T--)
	{
		cin>>n;
		init(a,n);
		sort(a,a+n);
		do
		{
			if(judge(a,n))
			{
				for(i=0;i<n;++i)
					cout<<a[i];
				cout<<endl;
			}
		}while(next_permutation(a,a+n));//该函数的功能是如果对于一个序列,存在按照字典排序后这个序列的下一个排列,那么就返回true且产生这个排列,否则返回false。
							//注意,为了产生所有的全排列,初始时这个序列应该是字典序最小的那个排列,即要调用一次sort(包含在algorithm头文件中)
	}
	return 0;
}

 

转载于:https://www.cnblogs.com/dongsheng/archive/2012/08/01/2618702.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值