tuki2501

So28_Bai4.cpp

Nov 4th, 2021
1,220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5.  
  6. const int N = 100005;
  7.  
  8. int n; ll m;
  9. int a[N], b[N], l[N], r[N];
  10.  
  11. bool check(int x) {
  12.   for (int i = 1; i <= n; i++) {
  13.     l[i] = r[i] = 0;
  14.   }
  15.   for (int i = 1; i <= n; i++) {
  16.     b[i] = a[i] >= x ? a[i] : x;
  17.   }
  18.   for (int i = 1; i <= n; i++) {
  19.     l[i] = i > 1 ? max(b[i], l[i - 1]) : b[i];
  20.   }
  21.   for (int i = n; i >= 1; i--) {
  22.     r[i] = i < n ? max(b[i], r[i + 1]) : b[i];
  23.   }
  24.   ll sum = 0;
  25.   for (int i = 1; i <= n; i++) {
  26.     sum += max(0, min(l[i - 1], r[i + 1]) - b[i]);
  27.   }
  28.   return sum >= m;
  29. }
  30.  
  31. signed main() {
  32.   cin.tie(0)->sync_with_stdio(0);
  33.   cin >> n >> m;
  34.   for (int i = 1; i <= n; i++) {
  35.     cin >> a[i];
  36.   }
  37.   int l = 0, r = 2e9, ans = -1;
  38.   while (l <= r) {
  39.     int x = l + (r - l) / 2;
  40.     if (check(x)) {
  41.       ans = x;
  42.       l = x + 1;
  43.     }
  44.     else {
  45.       r = x - 1;
  46.     }
  47.   }
  48.   cout << ans << '\n';
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment