codeforces-1201 C Maximum Median
二分查找的典型应用,寻找虚无的值代入测试
1 #include <bits/stdc++.h> 2 #define _for(i,a,b) for(int i = (a);i < b;i ++) 3 typedef long long ll; 4 using namespace std; 5 inline ll read() 6 { 7 ll ans = 0; 8 char ch = getchar(), last = ' '; 9 while(!isdigit(ch)) last = ch, ch = getchar(); 10 while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); 11 if(last == '-') ans = -ans; 12 return ans; 13 } 14 inline void write(ll x) 15 { 16 if(x < 0) x = -x, putchar('-'); 17 if(x >= 10) write(x / 10); 18 putchar(x % 10 + '0'); 19 } 20 ll n,k; 21 ll a[200006]; 22 bool C(ll d) 23 { 24 ll line = a[n/2]+d; 25 ll tmpk = k; 26 tmpk -= d; 27 _for(i,n/2+1,n) 28 if(a[i]<line) 29 tmpk -= line-a[i]; 30 else 31 break; 32 return tmpk>=0; 33 } 34 ll solve() 35 { 36 ll lb = 0,ub = 1000000002; 37 while(ub - lb > 1) 38 { 39 ll mid = lb+(ub-lb)/2; 40 if(C(mid)) lb = mid; 41 else ub = mid; 42 } 43 return lb; 44 } 45 int main() 46 { 47 n = read(),k = read(); 48 _for(i,0,n) 49 a[i] = read(); 50 sort(a,a+n); 51 ll rnt = solve(); 52 write(rnt+a[n/2]); 53 return 0; 54 }