题目描述
给定整数 n (1 < n≤ 6),编写程序以字典序列出n的所有错位排列序列。 所谓字典序即升序。 所谓错位排列指在数j不能在数列中第j个位置。
输入
输入包括多行,每行一个整数n
输出
每行输出一种排列,每行数字以空格相隔,以回车换行
样例输入
2
样例输出
2 1
我用穷举法做的,上代码:
#include <stdio.h> void cw2(int a[]) { printf("2 1 \n"); } void cw3(int a[]) { printf("2 3 1 \n"); printf("3 1 2 \n"); } void cw4(int a[]) { printf("2 1 4 3 \n"); printf("2 3 4 1 \n"); printf("2 4 1 3 \n"); printf("3 1 4 2 \n"); printf("3 4 1 2 \n"); printf("3 4 2 1 \n"); printf("4 1 2 3 \n"); printf("4 3 1 2 \n"); printf("4 3 2 1 \n"); } void cw5(int a[]) { int i, j, m, n, k, q; for(i = 2; i <= 5; i++){ a[0] = i; for(j = 1; j <= 5; j++){ if(j != a[0] && j != 2){ a[1] = j; for(m = 1; m <= 5; m++){ if(m != a[0] && m != a[1]&&m!=3){ a[2] = m; for(n = 1; n <= 5; n++){ if(n != a[0] && n != a[1] && n != a[2]&&n!=4){ a[3] = n; for(k = 1; k <= 4; k++){ if(k != a[0]&&k != a[1]&&k != a[2]&&k != a[3]){ a[4] = k; for(q = 0; q < 5; q++) printf("%d ", a[q]); printf("\n"); } } } } } } } } } } void cw6(int a[]) { int i, j, m, n, k, p, q,sum = 0; for(i = 2; i <= 6; i++){ a[0] = i; for(j = 1; j <= 6; j++){ if(j != a[0] && j != 2){ a[1] = j; for(m = 1; m <= 6; m++){ if(m != a[0] && m != a[1]&&m!=3){ a[2] = m; for(n = 1; n <= 6; n++){ if(n != a[0] && n != a[1] && n != a[2]&&n!=4){ a[3] = n; for(k = 1; k <= 6; k++){ if(k != a[0]&&k != a[1]&&k != a[2]&&k != a[3]&&k!=5){ a[4] = k; for(p = 1; p <= 5; p++){ if(p != a[0]&&p != a[1]&&p != a[2]&&p != a[3]&&p != a[4]){ a[5] = p; for(q = 0; q < 6; q++) printf("%d ", a[q]); printf("\n"); //sum++; } } } } } } } } } } } //printf("%d\n",sum); } void main() { int a[6] = {0}; int n; while(scanf("%d", &n) != EOF){ if(n == 2) cw2(a); else if(n == 3) cw3(a); else if(n == 4) cw4(a); else if(n == 5) cw5(a); else cw6(a); } } /************************************************************** Problem: 1711 User: 2012014425 Language: C Result: 正确 Time:0 ms Memory:768 kb ****************************************************************/