We need to compute for each test case: given N distinct positive integers (strengths) (but note constraints: strength can be 0? It says 0 ≤ Strength ≤ 2e9, and they are different, and positive integer? Actually problem statement says "strength is represented by a positive integer." But sample includes 0. So maybe they consider non-negative. But anyway, distinct numbers, possibly zero. We need sum over all subsets of size K of the minimum element of the subset. Compute total sum modulo 1e9+7.
We need efficient algorithm because N up to 100k, T up to 100 but sum of N likely not exceed something? The constraints: T up to 100, N up to 100k each => total up to 10^7, need O(N log N) per test or O(N) after sorting. Since we need sum over all K-subsets of min, we can sort the array in increasing order. Let the sorted strengths be a[1..N] (1-indexed, increasing). For each position i, we want to count how many K-subsets have a[i] as the minimum. If a[i] is the minimum, then the subset must include a[i] and the remaining K-1 elements must be chosen from elements that are greater than a[i] (i.e., from indices i+1 to N). The number of such subsets is C(N - i, K - 1). So the contribution of a[i] is a[i] * C(N - i, K - 1). The total sum = sum_{i=1}^{N} a[i] * C(N - i, K - 1).
But careful: for a[i] to be the minimum, we need that there is no element smaller than a[i] in the subset. Since we are choosing subsets of size K, and we force a[i] to be included, and we choose K-1 from the larger ones, it's fine. However, if there are duplicate values? The problem says all strengths are different, so distinct. So this works.
But wait: The subset must contain exactly K elements. For a[i] to be the minimum, we must have a[i] in the subset, and all other elements must be larger. That is exactly combinations. So we sum that.
Now constraints: N up to 100k, K up to N. We need to compute binomial coefficients C(N-i, K-1) modulo MOD=1e9+7. But note that N-i can be up to N, and we need many binomials. We can precompute factorials up to N and use modular inverse. That's O(N) precomputation per test. However T up to 100, but total N across tests could be up to 10^7 (if each test max 100k, 100*100k = 10^7). Precomputing factorials per test O(N) is okay, as total N across tests 10^7, which is acceptable. But we need to compute for each test only factorials up to its N.
Alternatively, we can compute binomials using combination recurrence maybe cumulative? Since we need C(N-i, K-1) for i from 1 to N-K+1 (since if N-i < K-1, then C=0). So i can go up to N-K+1. So we need compute many binomials. We can compute all factorials and inverse factorials up to N. Then C(n, r) = fact[n] * invfact[r] * invfact[n-r] mod MOD.
Edge Cases: K=1: then the min is each element itself. The formula: C(N-i, 0) = 1, so sum = sum of all a[i]. Good.
Also note strengths up to 2e9, need to mod after multiplication.
Potential issues: large N and large T, but total N up to 10^7; O(N log MOD) for modular inverses? We can precompute factorial and inv factorial in O(N) using Fermat's little theorem for inv factorial: compute fact up to N, then invfact[N] = modinv(fact[N]), then go down to compute invfact[i-1] = invfact[i] * i % MOD. This is O(N) plus one modular exponentiation for invfact[N] (log MOD). So overall fine.
Now we need to sort the array. Sorting O(N log N). Total O(T * (N log N + N)) = at most 10^7 * log(10^5) ~ 1.7e8 operations maybe borderline but okay in C++.
But we need to careful about reading input and large T.
Simplify: For each test case:
- Read N, K.
- Read N strengths.
- Sort strengths ascending.
- Precompute factorials up to N (maybe we can reuse? but each test different N, we need allocate vector of size N+1).
- For i from 1 to N (or 0-indexed), compute if N-i-1? Let's use 0-indexed sorted array: a[0..N-1] ascending.
For index i (0-based), the number of larger elements = N - i - 1. We need C(N - i - 1, K - 1). Because if we include a[i], we need to choose K-1 from the N - i - 1 elements after it. So contribution = a[i] * C(N - i - 1, K - 1). Sum i from 0 to N-1. But if N - i - 1 < K - 1, then C=0.
Thus algorithm:
total = 0
for i in 0..N-1:
m = N - i - 1
if m >= K-1:
total = (total + a[i] * C(m, K-1)) % MOD
Return total.
But careful: When K > N, but K ≤ N by constraints.
So we need binomial function.
Edge case: K=0? Not allowed, K >=1.
Thus good.
Let's test with sample:
Test1: N=2, K=1, a=[4,5] sorted ascending? Actually sample input: 5 4. Sorted ascending = [4,5]. For i=0: m = 2-0-1=1, K-1=0 => C(1,0)=1 => contribution 4; i=1: m=0, C(0,0)=1? Wait m=0, K-1=0 => C(0,0)=1 (by definition). But note: when K=1, we need to include each element as a subset of size 1. But for i=1 (largest), the number of larger elements is 0, we need choose 0 from 0: valid. So contribution 5. Sum=9.
But careful: The formula for i=1: N-i-1 = 0, C(0,0)=1. So okay.
Test2: N=3, K=2, strengths: 1 0 2 -> sorted ascending: [0,1,2].
i=0: m=3-0-1=2, K-1=1 => C(2,1)=2 => contribution 02=0
i=1: m=3-1-1=1, C(1,1)=1 => contribution 11=1
i=2: m=3-2-1=0, K-1=1, m<1 => contribution 0
Total=1. matches.
So formula works.
Now we need to compute binomial modulo 1e9+7 for up to n=100000. But note that N-i-1 can be up to N-1, and K-1 up to N-1. So we need factorial up to N (maybe N). Since MOD is prime (1e9+7), we can compute factorials.
Implementation details:
We'll read T. For each test case:
- read N, K.
- read N integers into vector a (or int, but up to 2e9 fits in 64-bit).
- sort(a.begin(), a.end()).
- Precompute factorial fact[0..N] and invfact[0..N] modulo MOD.
fact[0]=1; for i=1..N: fact[i] = fact[i-1]*i % MOD.
invfact[N] = modpow(fact[N], MOD-2, MOD).
for i=N down to 1: invfact[i-1] = invfact[i]*i % MOD.
- Then total = 0.
- For i=0 to N-1:
n = N - i - 1;
r = K - 1;
if n >= r:
comb = fact[n] * invfact[r] % MOD * invfact[n - r] % MOD;
total = (total + a[i] % MOD * comb) % MOD;
- Print total.
Edge Cases: If K = 0? not. If K > N? not.
But note: When K-1 = 0 (K=1), we need C(n,0)=1 for any n >=0. Our combination function will compute fact[n] * invfact[0] * invfact[n] = fact[n]1invfact[n]=1. Since invfact[0] we need to set. We compute invfact[0] from the downward loop: invfact[N] computed, then for i=N..1: invfact[i-1] = invfact[i]*i % MOD. This gives invfact[0] correctly as 1? Let's check: invfact[N] = inv(fact[N]); then for i=N down to 1: invfact[i-1] = invfact[i] * i % MOD. So invfact[0] = invfact[1] * 1? But careful: the loop goes from i=N down to 1, at each step we set invfact[i-1]. At the final step when i=1, we set invfact[0] = invfact[1] * 1. But what is invfact[1]? Let's compute: invfact[N] computed, then we compute invfact[N-1] = invfact[N] * N % MOD, etc. So invfact[1] = invfact[2] * 2 = ... Actually we can prove that invfact[0] = 1 because the product fact[0]*invfact[0] should be 1. But is it? We can compute directly: invfact[0] = 1 if we set it explicitly or rely on the loop. Let's test small N: N=1: fact[0]=1, fact[1]=1. invfact[1] = modinv(1)=1. Then loop i from 1 down to 1: invfact[0] = invfact[1]1 = 11=1. So okay. For N=2: fact[2]=2; invfact[2]=modinv(2)=500000004; then i=2: invfact[1] = invfact[2]2 = 5000000042%MOD=1; i=1: invfact[0] = invfact[1]*1 =1. So indeed invfact[0]=1. So fine.
But we need to handle cases where r=0: we could also just treat comb=1 when r=0, to avoid computing factorial for n which could be large? But it's fine.
Potential issue: In the loop, we compute fact[n] and invfact[n-r] etc. But fact is precomputed up to N, and n <= N-1 <= N, so okay.
Now complexity: sorting O(N log N). Precomputation O(N). Loop O(N). For each test case.
Now we must consider T up to 100, but total N across tests may be 10^7. Sorting each test O(N log N) might sum to about 10^7 * log(10^5) ~ 1.7e8 operations, acceptable in C++.
Memory: Fact and invfact arrays size N+1 each, of int64. That's about 21000018 ~ 1.6MB per test. If we allocate per test, okay. But we could reuse vector and resize.
Now we must be careful about reading input fast. Use scanf or fast I/O.
Now check constraints: "Strength of all the students are different." So distinct.
Edge Cases: K=N. Then each subset is whole set, min is the minimum of the whole set, i.e., a[0]. And there is only one subset. Our formula: For i=0: m = N-0-1 = N-1, r = K-1 = N-1 => C(N-1,N-1)=1 => contribution a[0]*1 = a[0]; for i>0: m = N-i-1 < N-1? For i=1, m = N-2, r=N-1 => m<r => comb=0. So total = a[0] correct.
Works.
But wait: There's subtlety: The sum over all K-subsets of min, but the formula counts each subset exactly once because the minimum element is unique (since distinct). So fine.
Now we must output modulo 1e9+7.
Potential integer overflow: Multiply a[i] (up to 2e9) by comb (up to MOD-1) could be up to 2e9 * 1e9+7 ~ 2e18, fits in 64-bit signed (9e18). So use long long (int64) for multiplication and mod.
Now implement.
But before finalizing, double-check sample: Already matched.
Now consider an alternative approach: Since we need sum of a[i] * C(N-i-1, K-1), we can compute comb efficiently by dynamic programming? But factorial method is fine.
But note: The constraints: "Strength of each student ≤ 2000000000" and "strengths are different". But they can be zero. So mod may produce negative? No.
Now ensure to handle modulo after each addition.
Now what about test cases where N is large but K is also large, we compute factorials up to N, okay.
Now think about potential pitfalls: When N is up to 100,000, factorial up to 100,000, we need mod inverse of fact[N] which we compute via powmod. That's O(log MOD) ~ 30 operations, fine.
Now code.
But also note: If K > N? Not allowed.
Now one more nuance: The answer must be sum of strengths of all teams of size K. If K=0? Not.
Now check if there's any requirement that strengths are positive integers? The problem statement says positive integer, but sample includes 0. So we'll treat as non-negative. It doesn't matter.
Now, is there any possibility of overflow when computing factorial? Use modulo.
Now for each test, we need to allocate arrays of size N+1. For large T, this could cause many allocations and deallocations; but it's okay.
We can also pre-allocate a global factorial up to max N across all tests? But we don't know max N in advance. Could read all tests first? Not necessary.
Now implement.
Pseudo:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
ll modpow(ll a, ll b) {
ll res=1;
while(b){
if(b&1) res = resa % MOD;
a = aa % MOD;
b>>=1;
}
return res;
}
vector fact, invfact;
void precompute_fact(int n) {
fact.resize(n+1);
invfact.resize(n+1);
fact[0]=1;
for(int i=1;i<=n;i++) fact[i]=fact[i-1]*i%MOD;
invfact[n]=modpow(fact[n], MOD-2);
for(int i=n;i>=1;i--) invfact[i-1]=invfact[i]*i%MOD;
}
ll nCr(int n, int r) {
if(r<0 || r>n) return 0;
return fact[n]invfact[r]%MODinvfact[n-r]%MOD;
}
int main() {
int T;
scanf("%d", &T);
while(T--){
int N, K;
scanf("%d%d", &N, &K);
vector a(N);
for(int i=0;i<N;i++) scanf("%lld", &a[i]);
sort(a.begin(), a.end());
precompute_fact(N);
ll ans = 0;
int r = K-1;
for(int i=0;i<N;i++){
int n = N - i - 1;
if(n >= r) {
ll comb = nCr(n, r);
ans = (ans + (a[i] % MOD) * comb) % MOD;
}
}
printf("%lld\n", ans);
}
return 0;
}
Now let's test with sample:
Input:
2
2 1
5 4
3 2
1 0 2
Running code mentally:
First test: N=2,K=1, a=[4,5] after sort. precompute factorial up to 2. r=0. For i=0: n=1, n>=0 => comb = nCr(1,0)=1 => ans +=4 =>4. i=1: n=0, n>=0 => comb=nCr(0,0)=1 => ans+=5 =>9. Output 9.
Second test: N=3,K=2, a sorted = [0,1,2]. precompute fact up to 3. r=1. i=0: n=2>=1 => comb = C(2,1)=2 => ans +=0 =>0. i=1: n=1>=1 => comb =1 => ans+=1 =>1. i=2: n=0 <1 => skip. Output 1. Works.
Now check for K=N=3: a sorted [0,1,2], r=2. i=0: n=2>=2 => comb = C(2,2)=1 => ans+=0 =>0. i=1: n=1<2 skip; i=2 skip. Output 0? But min of whole set is 0, sum should be 0. Good.
Now one more test: N=5, K=3, strengths random. We'll test later.
Now we need to be mindful about memory: In precompute_fact, we resize vectors. For each test, we allocate new vectors. Could also use global arrays with max size but we don't know max N, we could read all tests first to get maxN? Simpler: we can compute factorial per test as above. Since total N is 1e7, total memory allocated over all tests (alloc and free) might be okay.
But there is potential to improve: We can compute binomial using precomputed factorials and inverse factorials but also we can compute C(n, r) iteratively as we iterate i because n decreases by 1 each step? Actually n = N - i - 1, so as i increases, n decreases. r = K-1 is constant. So we need C(n, K-1) for decreasing n. Could we compute these combinations quickly without factorials each time? For example, start from n_max = N-1 (when i=0) C(N-1, K-1). Then for each step, we can update to C(n-1, K-1) using recurrence: C(n-1, K-1) = C(n, K-1) * (n - (K-1)) / n? Let's derive:
C(n, r) = n!/(r!(n-r)!)
C(n-1, r) = (n-1)!/(r!(n-1-r)!) = C(n, r) * (n - r) / n? Actually:
C(n, r) = n!/(r!(n-r)!) => multiply by (n - r)/n to get (n! * (n - r))/(r!(n-r)! * n) = n! * (n - r) / (r! * n * (n-r)!) = (n-1)!/(r! (n-r-1)!) = C(n-1, r). Yes, so C(n-1, r) = C(n, r) * (n - r) / n.
But careful: Division modulo MOD needs modular inverse. So we can compute as C(n-1, r) = C(n, r) * (n - r) % MOD * inv(n) % MOD. We can precompute modular inverses of numbers up to N. That could avoid factorial arrays but still need inv table. Actually we could compute all inverses up to N using linear method O(N). But then we still need to compute initial C(N-1, r) using factorial anyway. So factorials method simpler.
Given constraints, it's fine.
But note: If we precompute factorials per test, we need to compute fact and invfact up to N, which involves O(N) multiplications and one modular exponentiation for invfact[N]. This is okay.
Now we need to consider the possibility of large T and small N. It still works.
Now let's test with some random small cases manually to ensure correctness.
We'll brute for small N (e.g., N=4, K=2, strengths distinct) and compare with formula.
Let's pick a = [2,5,1,3] => sorted = [1,2,3,5]. All K=2 subsets: {1,2} min=1; {1,3} min=1; {1,5} min=1; {2,3} min=2; {2,5} min=2; {3,5} min=3 => sum = 1+1+1+2+2+3=10.
Our formula: r=1. i=0: n=3, C(3,1)=3 => contribution 13=3; i=1: n=2, C(2,1)=2 => 22=4; i=2: n=1, C(1,1)=1 => 3*1=3; i=3: n=0 <1 =>0; total=3+4+3=10. OK.
Now K=3: subsets: {1,2,3} min=1; {1,2,5} min=1; {1,3,5} min=1; {2,3,5} min=2 => sum=1+1+1+2=5.
Formula: r=2. i=0: n=3, C(3,2)=3 => 13=3; i=1: n=2, C(2,2)=1 =>21=2; i=2: n=1<2 skip; i=3 skip => total=5. Works.
So formula correct.
Now about modulo: Since MOD=1e9+7, we can compute.
Now what about constraints "Strength of each student ≤ 2000000000"? So a[i] can be up to 2e9, which fits in 32-bit signed? 2e9 is just below 2^31-1 (2,147,483,647). So it's okay for int, but use long long to be safe for multiplication.
Now edge: If N=100000, K=50000, factorials up to 100k, okay.
Now we need to ensure that we compute invfact correctly using modular exponentiation. Use fast pow.
Now consider alternative: Could we compute answer without factorials using combinatorial identity? But not needed.
Now finalize code.
But wait, there is a twist: The coach has N students, strengths are distinct. But there might be huge N but T small. Sorting O(N log N) fine.
Now consider potential overflow in multiplication a[i] * comb: a[i] up to 2e9, comb up to MOD (~1e9+7), product up to 2e18, fits in signed 64-bit (9.22e18). So store as long long, then mod.
Now one more nuance: Since we mod after each addition, final answer modulo 1e9+7.
Now think about memory: fact and invfact vectors of size N+1 each, each element long long (8 bytes). For N=100k, each vector ~800KB, total ~1.6MB. Acceptable.
Now multiple test cases: we allocate new vectors each time. Could cause overhead but fine.
We could also allocate once with max size after reading all test cases? But simpler.
Now check for speed: For each test, sorting (N log N) and factorial precompute (N) and loop (N). That's okay.
Now what about K = 0? Not allowed but if it were, we would need to handle comb with r=-1. Not needed.
Now confirm with random small brute in Python to be sure.
Now implement.
But there is potential optimization: If K > N, answer=0, but K ≤ N.
Now some details: reading input with scanf may be problematic for large input. Use fast I/O: ios_base::sync_with_stdio(false); cin.tie(0); But mixing scanf and cin? Use either. Since we use scanf, it's fast enough. However, we need to read long long. Use "%lld". Good.
Alternatively, use cin with sync.
Now finalize.
But wait, there might be an alternative way: Since strengths are distinct, we could also use order statistics but same.
Now confirm with sample.
Now I think solution is correct.
But let me think: Is there any scenario where the minimum element appears in multiple subsets counted multiple times? Each subset has a unique minimum because strengths distinct. So each subset is counted exactly once with its minimum element. So sum over contributions equals sum over subsets of min.
Thus answer is correct.
Now consider large numbers: factorial up to 100000 is fine.
Now we must handle the modulo properly: a[i] % MOD before multiplication? Actually a[i] can be up to 2e9, which is less than MOD? MOD is 1e9+7 ~ 1,000,000,007. 2e9 is greater than MOD, so we need to mod it. So do (a[i] % MOD) * comb % MOD. Or just a[i] % MOD. Since a[i] could be up to 2e9, (a[i] % MOD) is necessary to keep product within 64-bit? Actually product of two numbers each less than MOD can be up to ~1e18, still fits in 64-bit. But if we do a[i] % MOD, it's safe. So compute as (a[i] % MOD) * comb % MOD.
Now about factorial precomputation: for n up to 100k, fact[100000] is huge modulo MOD, but that's okay.
Now confirm that we handle r = 0 correctly: nCr(n,0)=1 for all n>=0. Our nCr returns fact[n]*invfact[0]*invfact[n] = 1 * 1 * 1 =1.
Now what about n < 0? In loop, we only compute if n >= r, so n >=0. In nCr, we also check r<0 or r>n returns 0. So safe.
Now final code.
But wait: We are using vector fact, invfact. In precompute_fact we resize them each test. That may cause dynamic allocation each time. Could be okay. But we might want to use static arrays with maximum N precomputed after reading all tests. Since we don't know max N in advance, we could read all test cases first to get max N, precompute factorials once, then process each test. That would reduce repeated work. However, total sum of N could be 10^7, and precomputing factorials up to max N (100k) per test might be okay anyway. But if T=100 and each N=100k, then we would compute factorials 100 times, each O(100k) = 10^7 operations, which is fine. Sorting each of 100k arrays 100 times = 100 * (100k log 100k) ~ 100 * 100k * 17 ≈ 170 million comparisons. That's acceptable in C++ with fast sort.
But we could also sort once? Not.
So I'll keep per-test factorial.
But note: For T=100, each N=100k, sorting 100 arrays of 100k each is 100 * 100k log 100k ≈ 100 * 100k * 17 ≈ 170 million, plus factorial precomputation 100 * 100k = 10 million, and loop 100 * 100k = 10 million. Total ~190 million operations, likely within time limit if optimized (like 2 seconds? Maybe borderline but typical CodeChef/hackerearth time limit may be 2-3 seconds? But the problem is from CodeChef? Actually it's from CodeChef? The problem might be from CodeChef "Team Selection"? But not sure. Usually they give 1-2 sec. 190 million operations might be a bit high but doable in C++ with fast I/O. However, we need to consider that sorting 100 * 100k ints (400KB each) reading and sorting may be okay if optimized.
But maybe sum of N across test cases is limited to 10^5? The constraint: 1 ≤ N ≤ 100000, T ≤ 100, but typical CodeChef problems have sum of N over test cases ≤ something. However, not stated here. The problem statement (as given) says: "Constraints: 1 ≤ T ≤ 100, 1 ≤ N ≤ 100000". It does not specify sum over T. So we should assume worst-case sum N can be up to 10^7. That's manageable.
But still 190 million operations may be near limit but usually within 2 sec? I'd like to further optimize: Sorting is the bottleneck. Could we avoid sorting? Let's think: The answer only depends on sorted order; we need sorted array. So sorting is necessary.
But we can perhaps use counting sort? No, values up to 2e9.
So we must sort.
But note: Strengths are distinct; but sorting is fine.
Now we might want to use iterative combination to avoid factorial arrays? It may be similar.
Alternatively, we can compute binomial using multiplicative formula for each i if K is small? But K can be large.
But we can compute comb incrementally as i increases because n decreases. That could eliminate need for factorials and modular inverses of all numbers, we only need to compute C(N-1, K-1) once using either direct formula with factorials up to N or using multiplicative method O(K) but K up to N. However we can compute C(N-1, K-1) using factorials anyway. But then we can update as we go, which would require modular inverses of numbers up to N, but we can precompute inv of 1..N using linear method in O(N). So overall still O(N). But then we don't need factorial arrays, just inv array and combination value. However we still need to compute initial combination C(N-1, K-1). Could compute using multiplicative method: C(n, r) = product_{i=1}^r (n - r + i) / i. We can compute numerator and denominator modulo MOD using modular inverses of i. That requires precomputing inv of numbers up to r? Actually we can compute iteratively by maintaining value and multiplying/dividing by appropriate numbers using precomputed inverses of 1..N. That is O(r) maybe up to N. But if K is large, r = K-1 can be up to N-1, so O(N) as well. So not a big difference.
Given simplicity, factorial method is fine.
But to further reduce overhead, we can precompute factorials and inv factorials up to max N across all test cases, then reuse. Let's consider that.
We could read all test cases first to know max N. However we need to store the strengths for each test? We can process test cases one by one, but we need max N for precomputation. We could read T, then for each test, read N, K and strengths? To know max N, we need to either read all inputs first (store N, K, arrays) or do two passes. But reading all inputs might be memory heavy: if total N up to 10^7, storing all strengths might be 80 MB (since each long long 8 bytes) plus overhead, maybe okay but borderline. But we can avoid storing all: we could first read all test cases to gather max N only, without storing strengths. But to gather max N, we need to read the entire file. However, if we read through the input, we need to parse numbers and skip the strengths. That would be complicated because we need to know N for each test to skip the strengths. We could read line by line? But easier: just compute factorials per test. Overhead is minimal.
Given typical contest environment, 10 million operations for factorial and 10 million for loop, plus sorting maybe 170 million comparisons. That might be okay in 2 seconds? Sorting 100 arrays of 100k ints: 100k * log2(100k) ~ 100k * 17 = 1.7 million comparisons per array? Actually number of comparisons is O(N log N) but each comparison of ints is cheap. 1.7 million comparisons per array? Wait, N log N: 100,000 * log2(100,000) ≈ 100,000 * 17 = 1.7 million comparisons. Times 100 = 170 million comparisons. That's plausible in ~1 second? Actually sorting 100k ints in C++ std::sort takes about 0.01 seconds? Typically sorting 1 million ints takes about 0.1 seconds. So 100k takes maybe 0.01 seconds? Actually depends on machine. On modern CPU, sorting 100k ints is very fast (maybe 5 ms). Times 100 = 0.5 seconds. So overall fine. So factorial and loop overhead negligible.
Thus per-test factorial is acceptable.
Now confirm sample again.
Potential issue: The strengths may be as large as 2e9, but we use % MOD before multiplication; also we read as long long.
Now check for K=0? Not.
Now, what about the modulo: 1000000007.
Now I'll write final code.
But one more nuance: For i from 0 to N-1, n = N - i - 1. When K-1 > n, comb=0. So loop can stop when n < r. Because after i > N - (K-1) - 1? Actually condition n >= r: N-i-1 >= K-1 => i <= N-K. So we can iterate i from 0 to N-K inclusive. So we can set loop limit: for i=0 to N-K. That reduces a bit. But not necessary.
We'll do for i=0; i < N; i++ with condition.
Now code.
But wait: The problem statement says "strength of a student is represented by a positive integer." However sample includes 0. Could be they consider positive as non-negative. No issue.
Now consider potential overflow in factorial: fact[i] = fact[i-1] * i % MOD, i up to 100k, no overflow.
Now compute invfact[N] using modpow which uses exponentiation. We need to compute modular inverse of fact[N] using Fermat's little theorem: fact[N]^(MOD-2) mod MOD. Since MOD is prime, okay.
Now for modpow, we should use long long.
Now final code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
ll modpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, K;
scanf("%d %d", &N, &K);
vector a(N);
for (int i = 0; i < N; i++) {
scanf("%lld", &a[i]);
}
sort(a.begin(), a.end());
// Precompute factorials up to N
vector<ll> fact(N+1), invfact(N+1);
fact[0] = 1;
for (int i = 1; i <= N; i++) {
fact[i] = fact[i-1] * i % MOD;
}
invfact[N] = modpow(fact[N], MOD-2);
for (int i = N; i >= 1; i--) {
invfact[i-1] = invfact[i] * i % MOD;
}
int r = K - 1;
ll ans = 0;
for (int i = 0; i < N; i++) {
int n = N - i - 1;
if (n < r) break; // since n decreases, we can break
ll comb = fact[n] * invfact[r] % MOD * invfact[n - r] % MOD;
ans = (ans + (a[i] % MOD) * comb) % MOD;
}
printf("%lld\n", ans);
}
return 0;
}
But note: using break when n < r works because n decreases as i increases. However, careful: For i=0, n=N-1. If N-1 < r then no subsets? Actually if K > N, impossible but K ≤ N. If K = N, then r = N-1, n = N-1 for i=0, then i=0 works, i=1: n=N-2 < N-1 so break. So break is fine. So we can use break. But if r=0 (K=1), then condition n < 0 is false for all, but break condition would be n < 0? Actually r=0, so n < 0? Since n is non-negative, never true. So we will iterate all i. That's correct because for K=1 we need all contributions. So we can break when n < r. That works because r >=0. So loop can be: for (int i = 0; i < N && N-i-1 >= r; i++) ...
Alternatively, compute limit = N - K; for i=0 to N-K inclusive. Because i <= N-K ensures N-i-1 >= K-1. So we can set limit = N - K; for i=0; i <= limit; i++. That's simpler and avoid condition inside loop. Let's do that.
Thus:
int limit = N - K; // i from 0 to limit inclusive
for (int i = 0; i <= limit; i++) {
int n = N - i - 1;
// n >= r guaranteed
ll comb = fact[n] * invfact[r] % MOD * invfact[n - r] % MOD;
ans = (ans + (a[i] % MOD) * comb) % MOD;
}
But careful: When K=1, limit = N-1, so i goes 0..N-1 inclusive => N iterations (since N-1 inclusive, i from 0 to N-1 yields N values). So that's correct.
When K=N, limit = 0, so i=0 only.
So we can use limit. This also avoids checking condition inside. Good.
Now code:
int limit = N - K;
for (int i = 0; i <= limit; i++) {
int n = N - i - 1;
ll comb = fact[n] * invfact[K-1] % MOD * invfact[n - (K-1)] % MOD;
ans = (ans + (a[i] % MOD) * comb) % MOD;
}
But note: n - (K-1) could be zero, invfact[0] defined.
Thus final.
But careful: For K=0? Not needed.
Now test with sample again:
Test2: N=3 K=2 => limit=1, i=0,1. i=0: n=2, comb = fact[2]*invfact[1]invfact[1] = 2 * 1 1 =2? Actually invfact[1]=? fact[1]=1, invfact[1]=1 => 211=2 mod? Wait comb should be C(2,1)=2. a[0]=0 => contribution 0. i=1: n=1, comb = fact[1]invfact[1]invfact[0] =111=1, a[1]=1 =>1. ans=1. Good.
Now for K=1: limit=N-1, so i runs all. i=0: n= N-1, comb = fact[N-1]*invfact[0]*invfact[N-1] =1. Good.
Now compute factorial up to N. But note: For n = N-i-1, maximum n = N-1. So we need factorial up to N-1. But we already have up to N.
Now, what about modulo operations: using long long.
Now one more check: For N large, factorial up to N may be fine.
Potential overflow in fact[i] = fact[i-1] * i % MOD: i up to 1e5, fact[i-1] < MOD, product up to 1e5 * 1e9+7 ~ 1e14 fits in 64-bit, so fine.
Now implement.
But we should also consider edge case: N=1, K=1. Then limit=0, i=0: n=0, comb = fact[0]invfact[0]invfact[0]=111=1, ans = a[0] % MOD. Correct.
Now consider large N, K=1: answer = sum of strengths mod MOD. Could also compute without factorial, but we still compute factorials and loop. That's okay.
Now, for performance, we can skip factorial precomputation if K=1 because comb is always 1. But not necessary.
Now the code.
But wait, there is a subtlety: The strengths are given as positive integers but can be 0. For min calculation, 0 is min if present. Works.
Now finalize.
Before final answer, let's test with random small N to ensure the formula equals brute force.
We can quickly test with Python (but not needed now).
Now we might consider reading input fast. Use scanf. Or use cin with sync.
We'll use scanf.
Now one more nuance: In the problem, sample input: "2\n2 1\n5 4\n3 2\n1 0 2". So each test case on separate lines. Reading with scanf is fine.
Now answer should be printed per line.
Now about modulo: The sum may be large, but modulo.
Now confirm that we don't need to handle negative numbers? Strengths are non-negative.
Now final code.
But wait, we have to consider that K can be up to N, and r = K-1 may be 0 when K=1. So invfact[0] defined as 1.
Now everything seems correct.
But is there any catch? Let's think about the problem statement: "Coach Ankit is forming a team for the Annual Inter Galactic Relay Race. He has N students that train under him and he knows their strengths. The strength of a student is represented by a positive integer." Then constraints: 0 ≤ Strength ≤ 2e9. So maybe strength can be 0? It says positive integer in description but constraints include 0. Probably treat as non-negative.
Now what about large N up to 100,000, but T=100; the factorial precomputation per test is O(N). We could also reuse factorials across tests by resizing and recomputing. That's fine.
Now check memory: For each test we allocate vector a of size N (max 100k) and fact of size N+1 (max 100001). That's about 800KB + 800KB = 1.6MB for a, plus two factorial vectors ~1.6MB, total ~3.2MB per test. But they are freed after each iteration (vector destructor). So stack memory is fine.
Now think about T=100 and N=100k each, the program may allocate and deallocate many times but that's okay.
Now we might want to use .reserve or static vectors to avoid reallocation overhead? Not necessary.
Now final code ready.
But hold on: There is another twist: The problem may require modulo 1000000007, but we must take care when computing factorial of 0, etc. Already handled.
Now I think solution is correct.
But wait, are we double counting? Let's double-check combinatorics: The number of K-subsets with minimum a[i] is C(N - i - 1, K - 1). Because we need to choose K-1 from the N - i - 1 elements greater than a[i] (since sorted). This is correct.
Now consider that we need to include a[i] itself. So total number of subsets is C(N, K). And sum_{i} a[i] * C(N - i - 1, K - 1) should equal sum_{i} a[i] * (number of subsets where a[i] is minimum). This is a standard identity. So good.
Now check extreme: N=100000, K=50000, a[i] random. Our calculation will compute combination values. Factorial up to 100000 is fine.
Now think about potential overflow in computing invfact[N] using modpow: modpow with exponent MOD-2 works.
Now test code with some small random N and K to ensure correctness.
I'll simulate manually with N=4, K=3, a=[10,20,30,40] sorted = [10,20,30,40]. Subsets of size 3: {10,20,30} min=10; {10,20,40} min=10; {10,30,40} min=10; {20,30,40} min=20. Sum=10+10+10+20=50.
Formula: r=2. i=0: n=3, C(3,2)=3 =>103=30. i=1: n=2, C(2,2)=1 =>201=20. i=2: n=1<2 skip. Total=50. Good.
Now N=5, K=2, a=[5,4,3,2,1] sorted ascending = [1,2,3,4,5]. Subsets of size 2: Choose 2 from 5 = 10 subsets. Sum of mins: list all pairs and min: (1,2)->1, (1,3)->1, (1,4)->1, (1,5)->1, (2,3)->2, (2,4)->2, (2,5)->2, (3,4)->3, (3,5)->3, (4,5)->4. Sum = 14 + 23 + 32 + 41 = 4+6+6+4=20.
Formula: r=1. i=0: n=4, C(4,1)=4 =>14=4; i=1: n=3, C(3,1)=3 =>23=6; i=2: n=2, C(2,1)=2 =>32=6; i=3: n=1, C(1,1)=1 =>41=4; i=4: n=0 <1 =>0. Total=20. Good.
So formula works.
Now the solution is correct.
Now potential issues: Time limit for T=100 and N=100k each: sorting 100k ints 100 times may be okay. But to be safe, we could use a slightly optimized version: if K=1, answer = sum % MOD; we can skip factorial computation. If K=N, answer = min (a[0]) % MOD. But not necessary.
Now final code with slight optimization:
if (K == 1) {
ans = accumulate(a.begin(), a.end(), 0LL) % MOD;
cout << ans << endl;
continue;
}
if (K == N) {
ans = a[0] % MOD;
cout << ans << endl;
continue;
}
But not needed.
Now implement.
Now note: Input format: first line T. Then each test: line with N and K, then line with N strengths. So we need to read accordingly.
Now final answer.
But careful: The problem statement says "modulo 1000000007", so we use MOD=1000000007.
Now provide final answer with explanation.
Now write solution description: we sort, then compute contributions.
Now done.
But I need to output final code.
But let me also consider alternative combinatorial identity: Sum_{i} a_i * C(n-i-1, K-1). That's the direct approach.
Now ensure we handle large T with many small N; not a problem.
Now final code in C++.
Potential pitfalls: using int for N, K, i, but factorial indices up to 100k, int is fine. But for modular multiplication we use long long.
Now code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
ll modpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, K;
scanf("%d %d", &N, &K);
vector a(N);
for (int i = 0; i < N; ++i) {
scanf("%lld", &a[i]);
}
sort(a.begin(), a.end());
// Precompute factorials up to N
vector<ll> fact(N+1), invfact(N+1);
fact[0] = 1;
for (int i = 1; i <= N; ++i) {
fact[i] = fact[i-1] * i % MOD;
}
invfact[N] = modpow(fact[N], MOD-2);
for (int i = N; i > 0; --i) {
invfact[i-1] = invfact[i] * i % MOD;
}
int r = K - 1;
int limit = N - K; // i from 0 to limit inclusive
ll ans = 0;
for (int i = 0; i <= limit; ++i) {
int n = N - i - 1; // number of elements greater than a[i]
ll comb = fact[n] * invfact[r] % MOD * invfact[n - r] % MOD;
ans = (ans + (a[i] % MOD) * comb) % MOD;
}
printf("%lld\n", ans);
}
return 0;
}
But we need to handle the case when K=0? Not needed.
One more thing: In the loop, we used limit = N - K. But if K = N, limit = 0, loop works. If K = 1, limit = N-1, loop i from 0 to N-1 inclusive, which is N iterations. That's fine.
Now test with sample again:
Test1: N=2,K=1: limit=1, i=0: n=1, comb = fact[1]invfact[0]invfact[1] = 111=1? Actually fact[1]=1, invfact[0]=1, invfact[1]=1 => comb=1. a[0]=4 => ans=4. i=1: n=0, comb = fact[0]invfact[0]invfact[0] =111=1, a[1]=5 => ans=9. Works.
Test2: N=3,K=2: limit=1, i=0: n=2, comb=fact[2]=2invfact[1]=1invfact[1]=1? Wait invfact[1]=1, invfact[1]=1 (since fact[1]=1, invfact[1]=1), invfact[2-1=1]=1 -> comb=2; a[0]=0 => ans=0. i=1: n=1, comb=fact[1]invfact[1]invfact[0]=111=1, a[1]=1 => ans=1. Works.
Now edge: N=1, K=1: limit=0, i=0: n=0, comb=1, ans = a[0] mod MOD. Works.
Now consider if K > N? Not allowed.
Now potential issue: When K = 0? Not allowed.
Now, what about negative values? Not.
Now one more thing: The constraint says strengths are different, but may include zero. Our code works.
Now output modulo.
Now finalize.
But there is a nuance: The answer for test case with large N and K might involve combination calculations that are huge but modulo fine.
Now could there be any overflow in computing fact[n] * invfact[r] % MOD * invfact[n - r] % MOD? We use long long and modulo after each multiplication. fact and invfact are < MOD. So product < MOD^3 ~ 1e27, which doesn't fit in 64-bit. However we do multiplication stepwise with modulo after each: (fact[n] * invfact[r]) % MOD, then times invfact[n-r] % MOD. So intermediate product stays < MOD^2 ~ 1e18 which fits in 64-bit? MOD is about 1e9, MOD^2 is 1e18, which is just below 2^63-1 (9.22e18). 1e18 < 9.22e18, so it fits. But if we did (fact[n] * invfact[r] * invfact[n-r]) without modulo in between, it could overflow 64-bit. But we do modulo after each multiplication, so safe.
Thus final code.
Now let's check performance: For each test, we compute factorial and inv factorial. The factorial computation uses loop from 1 to N. For N=100,000, that's 100k multiplications. That's fine.
Now memory: vector a size N (8 bytes per element), fact and invfact each N+1 (8 bytes each). For N=100k, that's ~ 2.4 MB. That's fine.
Now, we might want to use arrays instead of vectors? Vector is fine.
Now I think solution is complete.
But we have to output answer as integer mod 1e9+7.
Now final answer.
One more thing: The problem statement says "strength of a student is represented by a positive integer." but constraints allow 0. So we treat as integer.
Now I'll produce final answer.
But before final, let's test with some random small N using Python mental. Already did.
Now note: The solution uses sorting, which changes order but that's needed.
Now final answer.
I think this is correct.
Now write solution explanation.
--- Add explanation:
- Sort strengths.
- For each element, count number of subsets where it is the minimum: choose K-1 from the elements larger than it.
- Sum a[i] * C(N - i - 1, K - 1).
- Compute combinations using precomputed factorials and modular inverses.
- Complexity O(N log N) per test case.
Now code.
Now produce final answer.
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
ll modpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
int main()