TOJ 4003 Next Permutation

描述

It is an interesting exercise to write a program to print out all permutations of 1, 2, …, n. However, since there are 6227020800 permutations of 1, 2, …, 13, it is unlikely that we would ever run this program on an input of size more than 10.

However, here is another interesting problem whose solution can also be used to generate permutations. We can order the permutations of 1, 2, …, n under the lexicographic (or dictionary) order. Here are the permutations of 1,2,3 in lexicographic order:

   1 2 3     1 3 2     2 1 3     2 3 1     3 1 2     3 2 1
The problem we have is the following: given a permutation of 1,2, …, n, generate the next permutation in lexicographic order. For example, for 2 3 1 4 the answer is 2 3 4 1.
 

输入

The first line of the input contains two integers, N and K. This is followed by K lines, each of which contains one permutation of 1, 2,…,N.

 You may assume that 1 ≤ N ≤ 1000 and K ≤ 10.

输出

The output should consist of K lines. Line i should contain the lexicographically next permutation correponding to the permutation on line i+1 in the input.

 

样例输入

3 2
3 1 2
2 3 1

样例输出

3 2 1
3 1 2 

题目来源

TOJ

 

从数组的后面开始寻找(前面的数)小于(后面的数)的数字对,将它们交换,然后从(前面的数的位置+1)开始将到N-1的数从小到大排序。

寻找: (前面的数的位置i)从N-2到0,(后面的数的位置j)从N-1到i+1

 

#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    int N,K;
    int a[1010];
    while( scanf("%d %d",&N ,&K)!=EOF ){ 
        while(K--){
            for(int i=0; i<N; i++){
                scanf("%d",&a[i]);    
            }
            int flag=0;    
            for(int i=N-2; i>=0 && !flag; i--){
                for(int j=N-1; j>=i+1; j--){
                    if(a[i]<a[j]){
                        int t=a[j];
                        a[j]=a[i];
                        a[i]=t;                    
                        sort(a+i+1,a+N);
                        flag=1;
                        break;
                    }
                } 
            }
            flag=0;
            for(int i=0; i<N; i++){
                if(flag)printf(" ");
                printf("%d",a[i]);
                flag=1;
            }
            printf("\n");
        }
    } 
    return 0;
}

 

你可能感兴趣的:(ext)