蓝桥杯真题图书排列
填空题:将编号为 11 ~ 1010 的 1010 本书排放在书架上,要求编号相邻的书不能放在相邻的位置。请计算一共有多少种不同的排列方案。
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
// 定义返回值初始值
static int res = 0;
// 检查数组中两个元素是否相邻
public static boolean check(int a[]){
for(int i = 0; i < a.length - 1; i++){
if(Math.abs(a[i] - a[i + 1]) == 1){
return false;
}
}
return true;
}
// 交换a[]中的a[x],a[y]的值
public static void swap(int a[], int x, int y){
// int temp = a[x];
// a[x] = a[y];
// a[y] = temp;
if(x == y){
return;
}
a[x] ^= a[y];
a[y] ^= a[x];
a[x] ^= a[y];
}
// 深度优先遍历
public static void dfs(int a[], int begin, int end){
if(begin == end){
if(check(a))
res++;
}
for(int i = begin; i <= end; i++){
swap(a,begin,i);
dfs(a,begin+1,end);
swap(a,begin,i);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//在此输入您的代码...
int[] a = {1,2,3,4,5,6,7,8,9,10};
dfs(a,0,a.length-1);
System.out.println(res);
scan.close();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/8f8e7b30593770a5feea73b6716d2f70.png)