一个二分板子题
再来一遍:你咕评级真的水
通过这道板子题来看看二分需要注意的事情吧:
①ans要在check成立的条件下
②一定要搞明白是最大值最小还是最小值最大
#include<bits/stdc++.h>
#define int long long
#define fr(i,n) for(register int i = 1; i <= n; i++)
#define max(x,y) ((x)>(y)?(x):(y))
const int N = 1e6 + 9;
int h,n,m,a[N],ans = -0x3f3f3f,maxn=-0x3f3f3f;
inline int read()
{
int c = getchar();
int x = 0, f = -1;
if(c<’0’||c>’9’) {
if(c==’-‘) f = -1,c = getchar();
}
while(c>’0’ && c<’9’) x += (x<<1) + (x<<3) + c^48, c= getchar();
return x*f;
}
int check(int mid){
int sum = 0;
fr(i,n) if(a[i]>mid) sum += a[i] - mid;
if(sum >= m) return 1;
return 0;
}
signed main()
{
std::cin >> n >> m;
fr(i,n) std::cin >> a[i], maxn = max(a[i],maxn);
int l = 1, r = maxn;
while(l<r){
int mid = l + (r - l) /2;
if(check(mid)) {
l = mid + 1;
ans = max(ans,mid);
}
else r = mid;
}
std::cout << ans;
return 0;
}