---
title: "杰哥私房题──排列"
author: "netalpha"
date: "2009-03-10T17:25:48Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2009-03-10T17:25:48Z"
id: 346763
url: "https://netalpha.iteye.com/blog/346763"
---

问题：

大家知道，给出正整数n，则1 到n 这n 个数可以构成n！种排列，把这些排列按照从  
小到大的顺序（字典顺序）列出，如n=3 时，列出1 2 3，1 3 2，2 1 3，2 3 1，3 1 2，3 2 1  
六个排列。  
给出某个排列，求出这个排列的下k 个排列，如果遇到最后一个排列，则下1 排列为第  
1 个排列，即排列1 2 3…n。  
比如：n = 3，k=2 给出排列2 3 1，则它的下1 个排列为3 1 2，下2 个排列为3 2 1，因  
此答案为3 2 1。  
输入数据  
第一行是一个正整数m，表示测试数据的个数，下面是m 组测试数据，每组测试数据  
第一行是2 个正整数n( 1 &lt;= n &lt; 1024 )和k(1&lt;=k&lt;=64)，第二行有n 个正整数，是1，2 … n  
的一个排列。  
输出要求  
对于每组输入数据，输出一行，n 个数，中间用空格隔开，表示输入排列的下k 个排列。  
输入样例  
3  
3 1  
2 3 1  
3 1  
3 2 1  
10 2  
1 2 3 4 5 6 7 8 9 10  
输出样例  
3 1 2  
1 2 3  
1 2 3 4 5 6 7 9 8 10

 

```
#include <stdio.h>

int MyCompare(const void* e1, const void* e2){
	return *((int*) e1) - *((int*) e2);
}

int main(){
	int nCases;
	scanf("%d", &nCases);
	int an[1034], in,n;
	while(nCases --){
		int k;
		scanf("%d %d", &n, &k);
		for(in = 0; in < n ; in ++){
			scanf("%d", &an[in]);
		}
		int i,j,index = -1;
		for(i = 0; i < k; i ++){
			for(j = n -1; j >= 0; j--){
				if(an[j - 1] < an[j]){
					index = j - 1;
					break;
									}
			}
			int m;
			if(index == -1 ){
				int roop;
				for(roop = n ; roop > 0; roop --){
					printf("%d ", an[roop -1]);
				}
				printf("\n");
				return 0;	
			}
			int candidate = an[j], index2 = j;
			for(m = j; m < n; m++){
				if(an[m] > an[index] && an[m] < candidate){
					candidate = an[m];
					index2 = m;
				}
			}
			int swap = an[index];
			an[index] = candidate;
			an[index2] = swap;
			qsort(an + j, n - j , sizeof(int), MyCompare);
		}
	}
	int i;
	for(i = 0; i < n; i++){
		printf("%d ", an[i]);
	}
	printf("\n");
	return 0;
}
```