Skip to content

Commit 3fa3fe9

Browse files
authored
Merge pull request #513 from capricemoto/main
d8q1
2 parents 79282ba + 99cc10b commit 3fa3fe9

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

  • Problems/Mathematics/Day-08/sol/Samarth
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <bits/stdc++.h>
2+
#define endl '\n'
3+
#define in(a) for(int i = 0; i<a.size(); i++) cin>>a[i];
4+
typedef long long ll;
5+
6+
using namespace std;
7+
8+
/*
9+
PROBLEM STATEMENT:
10+
Sasha wants to buy an apartment on a street where the houses are numbered from 1 to 109
11+
12+
from left to right.
13+
14+
There are n
15+
bars on this street, located in houses with numbers a1,a2,…,an
16+
17+
. Note that there might be multiple bars in the same house, and in this case, these bars are considered distinct.
18+
19+
Sasha is afraid that by the time he buys the apartment, some bars may close, but no more than k
20+
21+
bars can close.
22+
23+
For any house with number x
24+
, define f(x) as the sum of |x−y| over all open bars y
25+
26+
(that is, after closing some bars).
27+
28+
Sasha can potentially buy an apartment in a house with number x
29+
(where 1≤x≤109) if and only if it is possible to close at most k bars so that after that f(x)
30+
31+
becomes minimal among all houses.
32+
33+
Determine how many different houses Sasha can potentially buy an apartment in.
34+
35+
36+
APPROACH:
37+
the median is the answer(if n is even then elemnts btwn & including n/2 &n/2+1) if no bars are closed;
38+
and we observe a pattern that if even bars are closed in even n the range increases to n/2-k/2 to n/2+1 +k/2;
39+
and if odd bars are closed in odd n then range becomes (n+1)/2-(k+1)/2 to (n+1)/2 +(k+1)/2;
40+
so we just implement the same ;
41+
42+
43+
TIME COMPLEXITY:O(nlogn) (to sort);
44+
45+
Submission link:
46+
https://codeforces.com/contest/2098/submission/356268443
47+
48+
49+
*/
50+
51+
52+
53+
54+
void solve(){
55+
int n,k;cin>>n>>k;vector<int>a(n);in(a);
56+
sort(a.begin(),a.end());
57+
if(n&1){
58+
cout<<a[(n+1)/2+(k+1)/2-1]-a[(n+1)/2-(k+1)/2-1]+1<<endl;
59+
}
60+
else{
61+
cout<<a[n/2+k/2]-a[n/2-k/2-1]+1<<endl;
62+
}
63+
}
64+
65+
int main(){
66+
ios::sync_with_stdio(0); cin.tie(0);
67+
int t;cin>>t;
68+
while(t--)
69+
solve();
70+
71+
}

0 commit comments

Comments
 (0)