描述 Description
Matrix67 发现身高接近的人似乎更合得来。Matrix67 举办的派对共有 N(1<=N<=10) 个人参加,Matrix67 需要把他们安排在圆桌上。Matrix67 的安排原则是,圆桌上任意两个相邻人的身高之差不能超过 K。请告诉 Matrix67 他共有多少种安排方法。
输入格式 InputFormat
第一行输入两个用空格隔开的数 N 和 K,其中 1<=N<=10,1<=K<=1 000 000。
第二行到第 N+1 行每行输入一个人的身高值。所有人的身高都是不超过 1 000 000 的正整数。
输出格式 OutputFormat
输出符合要求的安排总数。
样例输入 SampleInput
10 1
5
5
5
5
5
5
5
5
5
5
样例输出 SampleOutput
362880
代码 Code
水。
#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int a[11];
bool b[11];
int f[11];
int i,j,t,n,m,l,r,k,z,y,x,ans;
void dfs(int s)
{
int i,j,t;
if (s==n)
{
for (i=1;i<=n;i++) if (b[i]==false && abs(a[i]-a[f[1]])<=k && abs(a[i]-a[f[s-1]])<=k) ans++;
return ;
}
for (i=1;i<=n;i++) if (b[i]==false && abs(a[i]-a[f[s-1]])<=k)
{
f[s]=i;
b[i]=true;
dfs(s+1);
b[i]=false;
}
}
int main()
{
scanf("%d%d",&n,&k);
for (i=1;i<=n;i++) scanf("%d",&a[i]);
ans=0;
memset(b,false,sizeof(b));
f[1]=1;
b[1]=true;
if (n==1) ans=1;
else dfs(2);
printf("%d\n",ans);
return 0;
}