【二分答案】洛谷P1873 砍树

前言

由于本题已经做过,当之前没有写博客,所以这里补上

链接

https://www.luogu.org/problemnew/show/P1873

大意

给出 n 个树木,现要砍掉一定树木,在使剩下的树木尽量多的情况下使砍掉的高度最大

思路

剩下的尽量多,却要求砍掉的高度最大,类似于最少……最大……问题,可以通过二分答案来解决

代码

#include<cstdio>
#include<algorithm>
using namespace std;
long long countt;
int mid,n,m,maxx,l,r,a[1000001],f,ans;char c;
int read()
{
    f=0;
    while (c=getchar(),c<=47||c>=58);f=(f<<3)+(f<<1)+c-48;
    while (c=getchar(),c>=48&&c<=57) f=(f<<3)+(f<<1)+c-48;
    return f;
}
int main()
{
    n=read();m=read();
    for (int i=1;i<=n;i++)
     a[i]=read(),maxx=max(a[i],maxx);r=maxx;l=0;
    while (l<=r)
    {
        mid=(l+r)>>1;
        countt=0;
        for (int i=1;i<=n;i++) countt+=max(0,a[i]-mid);//求出剩余高度和,因为树木高度不可能为负数,所以要求与0的最大值
        if (countt<m) r=mid-1;
        else l=(ans=mid)+1;
    }
    printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/xuxiayang/article/details/81630477