Luogu P1873 砍树 (二分)

一个二分板子题

再来一遍:你咕评级真的水

通过这道板子题来看看二分需要注意的事情吧:

①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;
}
posted @ 2019-11-05 11:13  QUEKI嶺冬  阅读(167)  评论(0编辑  收藏  举报
/*! Color themes for Google Code Prettify | MIT License | github.com/jmblog/color-themes-for-google-code-prettify */ .pln{color:#4d4d4c}ol.linenums{margin-top:0;margin-bottom:0;color:#8e908c}li.L0,li.L1,li.L2,li.L3,li.L4,li.L5,li.L6,li.L7,li.L8,li.L9{padding-left:1em;background-color:#fff;list-style-type:decimal!important;}@media screen{.str{color:#718c00}.kwd{color:#8959a8}.com{color:#8e908c}.typ{color:#4271ae}.lit{color:#f5871f}.pun{color:#4d4d4c}.opn{color:#4d4d4c}.clo{color:#4d4d4c}.tag{color:#c82829}.atn{color:#f5871f}.atv{color:#3e999f}.dec{color:#f5871f}.var{color:#c82829}.fun{color:#4271ae}} /*下面是我设置背景色,字体大小和字体*/ .cnblogs-markdown code{ background:#fff!important; } .cnblogs_code,.cnblogs_code span,.cnblogs-markdown .hljs{ font-size:16px!important; } .syntaxhighlighter a, .syntaxhighlighter div, .syntaxhighlighter code, .syntaxhighlighter table, .syntaxhighlighter table td, .syntaxhighlighter table tr, .syntaxhighlighter table tbody, .syntaxhighlighter table thead, .syntaxhighlighter table caption, .syntaxhighlighter textarea { font-size: 16px!important; } .cnblogs_code, .cnblogs_code span, .cnblogs-markdown .hljs{ font-family:consolas, "Source Code Pro", monaco, monospace !important; } //以上是代码高亮 /* 文字特效 */