此题与POJ3258有点类似,一开始把判断条件写错了,wa了两次,二分查找可以有以下两种:
while(ub-lb>0){ mid=(lb+ub)/2; if(C(mid)<=m) ub=mid; else lb=mid+1; //此时下限过小 } out(ub);//out(lb)
我一开始是写的下面这种,下面这种要单独判断lb和ub的值,因为用下面这种判断lb,ub都可能成立
while(ub-lb>1){ mid=(lb+ub)/2; if(C(mid)<=m) ub=mid; else lb=mid; } if(C(lb)<=m){ out(lb); } else out(ub);
二分查找的边界判断一定要灵活
/* * Created: 2016年03月31日 20时32分15秒 星期四 * Author: Akrusher * */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <string> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> #include <iomanip> #include <bitset> #include <sstream> #include <fstream> using namespace std; #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define in(n) scanf("%d",&(n)) #define in2(x1,x2) scanf("%d%d",&(x1),&(x2)) #define inll(n) scanf("%I64d",&(n)) #define inll2(x1,x2) scanf("%I64d%I64d",&(x1),&(x2)) #define inlld(n) scanf("%lld",&(n)) #define inlld2(x1,x2) scanf("%lld%lld",&(x1),&(x2)) #define inf(n) scanf("%f",&(n)) #define inf2(x1,x2) scanf("%f%f",&(x1),&(x2)) #define inlf(n) scanf("%lf",&(n)) #define inlf2(x1,x2) scanf("%lf%lf",&(x1),&(x2)) #define inc(str) scanf("%c",&(str)) #define ins(str) scanf("%s",(str)) #define out(x) printf("%d\n",(x)) #define out2(x1,x2) printf("%d %d\n",(x1),(x2)) #define outf(x) printf("%f\n",(x)) #define outlf(x) printf("%lf\n",(x)) #define outlf2(x1,x2) printf("%lf %lf\n",(x1),(x2)); #define outll(x) printf("%I64d\n",(x)) #define outlld(x) printf("%lld\n",(x)) #define outc(str) printf("%c\n",(str)) #define pb push_back #define mp make_pair #define fi first #define se second #define SZ(x) ((int)(x).size()) #define mem(X,Y) memset(X,Y,sizeof(X)); typedef vector<int> vec; typedef long long ll; typedef pair<int,int> P; const int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1}; const int INF=0x3f3f3f3f; const ll mod=1e9+7; ll powmod(ll a,ll b) {ll res=1;a%=mod;for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;} const bool AC=true; int n,m,maxn,sum; int a[100005]; int C(int x){ //计算额度为x时的最小month数 int last,cur,total,ans; last=cur=0;ans=0; while(true){ //注意循环终止条件 if(last>=n) break; total=a[last]; ans++; cur++; if(cur>=n) break; while(total+a[cur]<=x){ total+=a[cur]; cur++; if(cur>=n) break; } last=cur; } return ans; } int main() { in2(n,m); maxn=sum=0; rep(i,0,n){ in(a[i]); maxn=max(maxn,a[i]); sum+=a[i]; } int lb,ub,mid; lb=maxn;//额度下限 ub=sum;//额度上限 while(ub-lb>0){ //上下限相等时跳出循环 mid=(lb+ub)/2; if(C(mid)<=m) ub=mid; else lb=mid+1; //下限小了 } out(ub); return 0; }