题目描述:
题解
将琴键从小到大排列,然后从前往后遍历(i from 0 to n - m),每次选 m 个数时,下标为 i 的数都是最大的,所以再去下标为 i 的数的右边选 m - 1 个数,因此答案每次累加
a
[
i
]
∗
C
n
−
i
−
1
m
−
1
a[i]*C_{n - i - 1}^{m-1}
a[i]∗Cn−i−1m−1。
注意 0 的阶乘为 1,还要注意求乘法逆元使用费马小定理时模数 M 要为质数,求的是 M - 2 次方
AC Codes:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
using ll = long long;
const int N = 1e6 + 6, M = 1e9 + 7;
int a[N];
ll fac[N];
ll fastpow(ll a, ll n) {
ll res = 1, base = a;
while (n) {
if (n & 1) res = res * base % M;
base = base * base % M;
n >>= 1;
}
return res;
}
ll inv(ll a) {
return fastpow(a, M - 2L);
}
ll comb(ll n, ll k) {
if (k > n) return 0;
return fac[n] * inv(fac[k]) % M * inv(fac[n - k]) % M;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
fac[0] = 1;
for (int i = 1; i <= 1000000; i++) fac[i] = fac[i - 1] * i % M;
int T;
cin >> T;
while (T--) {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n, greater<int>());
ll ans = 0;
for (int i = 0; i <= n - m; i++) {
ans = (ans + a[i] * comb(n - i - 1, m - 1) % M) % M;
}
cout << ans << '\n';
}
return 0;
}