题目链接: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);
}
本文通过一个具体的在线评测题目介绍了使用二分法解决森林树木生长问题的过程,并分享了作者在实现过程中遇到的溢出问题及解决方案。
383

被折叠的 条评论
为什么被折叠?



