Codeforces 1462E2 Close Tuples (hard version)

题意

给一个长度为(n)的数组,取(m)个数字,其中最大值最小值相差不大于(k),问这种方式有多少种,答案(mod 10^9+7)

分析

通过简单版本大概了解了这题要枚举最小值来判断个数,那么我们枚举最小值(i),其他的数都要在([i,i+k])中取,而不能全部都在([i+1,i+k])中取,否则与枚举的最小值(i)不符。

采用容斥原理,将在([i,i+k])取数的情况减去在([i+1,i+k])取数的情况即可。

组合数可以预处理,也可以采用预处理阶乘处理,也可以使用卢卡斯定理。(预处理时记得控制空间)

#pragma GCC optimize(3, "Ofast", "inline")

#include <bits/stdc++.h>

#define start ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define ull unsigned long long
#define int ll
#define ls st<<1
#define rs st<<1|1
#define pii pair<int,int>
#define rep(z, x, y) for(int z=x;z<=y;++z)
#define repd(z, x, y) for(int z=x;z>=y;--z)
#define com bool operator<(const node &b)const
using namespace std;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
const int maxn = (ll) 4e5 + 5;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
int T = 1;
int num[maxn];
int sum[maxn];
int c[(ll) 2e5 + 5][105];

void solve() {
    int n, m, k;
    cin >> n >> m >> k;
    rep(i, 1, 2 * n)num[i] = sum[i] = 0;
    rep(i, 1, n) {
        int x;
        cin >> x;
        ++num[x];
    }
    rep(i, 1, 2 * n)sum[i] = sum[i - 1] + num[i];
    int ans = 0;
    rep(i, 1, n) {
        ans = (((ans + c[sum[i + k] - sum[i - 1]][m]) % mod - c[sum[i + k] - sum[i]][m]) % mod + mod) % mod;
    }
    cout << ans << '
';
}

signed main() {
    start;
    c[0][0] = 1;
    c[1][0] = c[1][1] = 1;
    rep(i, 2, 2e5) {
        c[i][0] = 1;
        rep(j, 1, 100) {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    cin >> T;
    while (T--)
        solve();
    return 0;
}
原文地址:https://www.cnblogs.com/F-Mu/p/14143108.html