题目链接:https://ac.nowcoder.com/acm/contest/984/C/
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

Farmer John is calling his N (1 <= N <= 10) cows to a very important meeting at a round table.
The cows are rather anxious about this meeting since they want to put forth their very best image. To make the table arrangement attractive, they want to ensure that any two cows sitting next to each other to differ in height by no more than K (1 <= K <= 1,000,000) millimeters (cow i has integer height Hi (1 <= Hi <= 1,000,000) millimeters).
Help calculate the number of ways the cows can sit down at the round table such that no two adjacent cows differ in height by more than K millimeters. Two ways are different if there is at least one cow with a different cow to its left in each arrangement.
The answer is guaranteed to fit in a 32-bit signed integer.

输入描述

Line 1: Two space-separated integers, N and K
Lines 2..N+1: Line i+1 contains height Hi

输出描述

Line 1: The number of ways that the cows can sit down at the round table such that two adjacent cows do not differ in height by more than K millimeters.

输入

4 10
2
16
6
10

输出

2

说明

There are 4 cows, with heights 2, 16, 6, and 10. Two cows whose heights differ by more than 10 do not want to sit next to each other.
Clearly the cows with heights 2 and 16 must be opposite each other, so there are 2 ways to place the cows of height 6 and 10.

解题思路

题意:n个数字组成一个环,使得相邻之间的差距不超过k,有几种组合方法。
思路:暴力枚举排列。

Accepted Code:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 15;
int vis[MAXN], arr[MAXN], h[MAXN];
int n, k, ans = 0;
void DFS(int p) {
    if (p == n) {
        ans++;
        return ;
    }
    for (int i = 0; i < n; i++) {
        if (vis[i] != 1 && abs(arr[p - 1] - h[i]) <= k) {
            if (p == n - 1 && abs(h[i] - arr[0]) > k)
                continue;
            arr[p] = h[i];
            vis[i] = 1;
            DFS(p + 1);
            vis[i] = 0;
        }
    }
}
int main() {
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; i++)
        scanf("%d", &h[i]);
    arr[0] = h[0];
    vis[0] = 1;
    DFS(1);
    printf("%d\n", ans);
    return 0;
}