二段性:如果高度(h)满足要求,那么所有的满足(le h)的高度都满足,若(h)不满足,那么所有(ge h)的都不满足。
二分答案,找满足要求的最大(h)
复杂度:(O(nlog(1e9)) = O(n), n le 1e6)
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int h[N];
int n, m;
int check(int x){
int sum = 0;
for(int i = 1; i <= n; i ++){
if(x < h[i]) sum += h[i] - x;
if(sum >= m) return 1;
}
return 0;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++) cin >> h[i];
int l = 0, r = 1e9;
while(l < r){
int mid = l + r + 1 >> 1;
if(check(mid)) l = mid;
else r = mid - 1;
}
cout << l << endl;
return 0;
}