Skip to content

Commit 9beb1d3

Browse files
authored
Add Solution2.cpp for binary array median problem
1 parent 5f31694 commit 9beb1d3

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
//submission: https://codeforces.com/problemset/submission/1999/356309382
2+
// P.S.: Given a binary array arr of length n and an integer k. Need to
3+
// find sum of median of all subsequences of arr. Ans. should be modulo 1e9+7
4+
5+
#include <bits/stdc++.h>
6+
#define ll long long
7+
8+
using namespace std;
9+
10+
const int MOD = 1e9+7;
11+
// The precomputation is O(N) and each test case is O(K)
12+
ll power(ll base, ll exp) {
13+
ll res = 1;
14+
base %= MOD;
15+
while (exp > 0) {
16+
if (exp % 2 == 1) res = (res * base) % MOD;
17+
base = (base * base) % MOD;
18+
exp /= 2;
19+
}
20+
return res;
21+
}
22+
23+
ll modInverse(ll n) {
24+
return power(n, MOD - 2);
25+
}
26+
27+
const int MAX = 200005;
28+
ll fact[MAX], invFact[MAX];
29+
30+
void precompute() {
31+
fact[0] = 1;
32+
for (int i = 1; i < MAX; i++) fact[i] = (fact[i - 1] * i) % MOD;
33+
invFact[MAX - 1] = modInverse(fact[MAX - 1]);
34+
for (int i = MAX - 2; i >= 0; i--) invFact[i] = (invFact[i + 1] * (i + 1)) % MOD;
35+
}
36+
37+
ll nCr(int n, int r) {
38+
if (r < 0 || r > n) return 0;
39+
ll num = fact[n];
40+
ll den = (invFact[r] * invFact[n - r]) % MOD;
41+
return (num * den) % MOD;
42+
}
43+
44+
void solve() {
45+
int n, k;
46+
cin>>n>>k;
47+
int c1 = 0;
48+
for (int i = 0; i < n; i++) {
49+
int x;
50+
cin >> x;
51+
if (x == 1) c1++;
52+
}
53+
int c0 = n - c1;
54+
55+
ll ans = 0;
56+
int min_ones = (k + 1) / 2;
57+
58+
// Median is 1 if we pick i ones where i >= (k+1)/2
59+
for (int i = min_ones; i <= k; i++) {
60+
if (i <= c1 && (k - i) <= c0) {
61+
ll ways = (nCr(c1, i) * nCr(c0, k - i)) % MOD;
62+
ans = (ans + ways) % MOD;
63+
}
64+
}
65+
cout << ans << "\n";
66+
}
67+
// T.C.: O(MAX+T*K)
68+
// S.C.: O(MAX)
69+
70+
int main() {
71+
// Fast I/O
72+
ios_base::sync_with_stdio(false);
73+
cin.tie(NULL);
74+
75+
precompute();
76+
77+
int t;
78+
if (!(cin >> t)) return 0;
79+
while (t--) {
80+
solve();
81+
}
82+
return 0;
83+
}

0 commit comments

Comments
 (0)