按照 $ h $ 降序依次放每个积木,此时如果有 \(2\) 块积木,那么一定满足条件。因为 \(h_{\text{now}} - h_{\text{pre}} \leq 0 \leq D\)。
继续往下想,再加一块,也要满足 $ h_{\text{next}} - h_{\text{now}} \leq D $。一旦不满足这个条件,后续即使插入更小的积木,也不合法。
每个积木 $ x $ 可以在 $[h_x, h_x + D] $ 的积木中任意选择一个并插入在下方。每次操作基本独立,根据乘法原理,总方案数是每次选法的乘积。
总复杂度 $ O(n \log n) $,瓶颈在于排序。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 6.2e5 + 5, mod = 1e9 + 9;
int n, D, a[N];
signed main() {ios::sync_with_stdio(false);cin.tie(0);cin >> n >> D;for (int i = 1; i <= n; i++) {cin >> a[i];}a[0] = 1;sort(a + 1, a + 1 + n);for (int i = 2, j = 1; i <= n; i++) {for (; a[i] - a[j] > D; j++); //用双指针求出每次的选法数量a[0] = a[0] * (i - j + 1) % mod;}cout << a[0];return 0;
}