题目描述:
一个数组长度为 $ n $ ,且为奇数。每次可以选择一个元素将其加 $ 1 $ ,最多进行 $ k $ 次操作,希望升序数组中位数尽可能大。
数据范围:
$ 1\le n \le 2 \times 10^5,1\le k \le 10^9, 1\le a_i \le 10^9 $
题解:
对中位数进行二分,然后进行 check
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| using namespace std; using namespace FAST_IO; const ll mod = 1e9 + 7; const int INF = 0x3f3f3f3f; const ll INF_LL = 0x3f3f3f3f3f3f3f3f; const double eps = 1e-5; const int maxn = 2e5 + 10; const int maxm = 1e5 + 10; int t, n, m, k; int a[maxn];
bool check(int x) { ll ans = 0; for (int i = n / 2 + 1; i <= n; i++) { if (a[i] < x) { ans += x - a[i]; } else { break; } } return ans <= k; } int main() {
#ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif read(n, k); for (int i = 1; i <= n; i++) { read(a[i]); } sort(a + 1, a + 1 + n); ll l = a[n / 2 + 1]; ll r = a[n] + k; int ans; while (l <= r) { int mid = l + ((r - l) >> 1); if (check(mid)) { l = mid + 1; ans = mid; } else { r = mid - 1; } } printf("%d\n", ans); return 0; }
|