• TOJ3072 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;
    }
    
    功不成,身已退
  • 相关阅读:
    printf和sprintf
    操作数、运算符、表达式
    全自动加法机
    Ascll、GB2312、Ansi
    数组
    循环
    编程命名规范
    浮点数及缺陷
    Android编码规范
    RGB着色对照表
  • 原文地址:https://www.cnblogs.com/dongsheng/p/2618702.html
Copyright © 2020-2023  润新知