CodeChef Forest Gathering —— 二分

本文通过一个具体的在线评测题目介绍了使用二分法解决森林树木生长问题的过程,并分享了作者在实现过程中遇到的溢出问题及解决方案。

题目链接:https://vjudge.net/problem/CodeChef-FORESTGA



题解:

现场赛。拿到这题很快就知道是二分,但是一直wa,怎么修改也wa,后来又换了种错误的思路,最后还是觉得二分是正确的,但还是wa。人生,就是在这些瞬间被怀疑的……

结束后,才发现,test()的时候溢出了。应该把判断放在循环里面,如果达到要求的,就立刻返回。因为达到要求后,后面的运算都是多余的。



反思:

在某些判断中,如果达到要求后,就立刻执行。不要等所有操作完成后,再执行,因为可能出现意想不到的结果。



代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
#define ms(a,b) memset((a),(b),sizeof((a)))
//#define LOCAL
using namespace std;
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int mod = 1e9+7;
const int maxn = 1e5+10;
const double pi = acos(-1.0);

LL n,w, li;
int h[maxn], r[maxn];

bool test(LL m)
{
    LL s = 0;
    for(int i = 1; i<=n; i++)
    {
        LL t = 1LL*h[i]+1LL*m*r[i];
        if(t<li) continue;
        s += t;
        if(s>=w)
            return 1;
    }
    return 0;
}

//bool test(LL m)
//{
//    LL s = 0;
//    for(int i = 1; i<=n; i++)
//    {
//        LL t = 1LL*h[i]+1LL*m*r[i];
//        if(t<li) continue;
//        s += t;
//    }
//    return s>=w;  //加完再判断会溢出。
//}


int main()
{
    scanf("%lld%lld%lld",&n,&w,&li);
    for(int i = 1; i<=n; i++)
        scanf("%d%d",&h[i],&r[i]);

    LL l = 0, r = 1e18;
    while(l<r)
    {
        LL m = (l+r)>>1;
        if(test(m))
            r = m;
        else
            l = m + 1;
    }
    printf("%lld\n",r);
}




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值