Skip to content

Commit bd0b3d8

Browse files
authored
Add Solution1.cpp for Maths day-8 p1
Implement solution for Codeforces problem 2098, calculating the range of medians after removing up to k bars.
1 parent 5f31694 commit bd0b3d8

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// submission: https://codeforces.com/contest/2098/submission/356344573
2+
3+
// we have houses numbered from 1 to 1e9 and n bars in houses a1,a2,.....,an (there can be multiple bars in single house)
4+
//and also an int k: at max k bars can be closed
5+
// For any house with number x, define f(x) as the sum of |x−y| over all open bars y (that is, after closing some bars).
6+
// sasha can buy apartment in a house with no. x if f(x) is minimal among all houses considering k constraint
7+
// Find the no. of different houses sasha can take apartment in
8+
9+
10+
#include <bits/stdc++.h>
11+
using namespace std;
12+
13+
using ll = long long;
14+
#define all(x) (x).begin(), (x).end()
15+
16+
const int MOD = 1e9 + 7; // 998244353
17+
const ll INF = 1e18;
18+
// It was simply finding the range of medians possible after removing the k elements. The range difference is the answer
19+
void solve() {
20+
int n,k;
21+
cin>>n>>k;
22+
vector<ll> a(n);
23+
for(auto &x: a) cin>>x;
24+
//sort the array for finding median
25+
sort(all(a));
26+
// find the worst case median after removing k bars from right
27+
int idx=(n-k-1)/2;
28+
cout<<a[n-1-idx]-a[idx]+1<<endl; //range difference is the answer
29+
}
30+
//T.C: O(t*n*logn) ; S.C.: O(1)
31+
32+
int main() {
33+
// Fast I/O
34+
ios::sync_with_stdio(false);
35+
cin.tie(nullptr);
36+
37+
int t;
38+
cin >> t;
39+
while (t--) {
40+
solve();
41+
}
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)