poj 3273 二分
题意:在n天里,Farmer John每天花a[i]元钱,把这些天分成连续的m份,要让最大的和尽量小,求这个和。
分析:a[i]最大为max,总和为sum,则答案一定在max到sum之间。二分答案ans,遍历a[],若能将a[]分成m份,每份的总和<=ans,则ans为一个可行解,若ans可行,ans-1不可行,则ans为最终答案。
const int N = 100005; int a[N]; int n, m, low, high; bool check(int lim){ int cnt=1, temp=0; FOR(i, 0, n){ temp += a[i]; if(temp > lim){ temp = a[i]; cnt++; } } if(cnt>m) return false; return true; } int main(){ #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); #endif scanf("%d%d",&n,&m); FOR(i, 0, n) { scanf("%d",&a[i]); high += a[i]; checkmax(low, a[i]); } while(low<high){ //cout<<low<<' '<<high<<' '<<endl; int lim = (low + high)/2; if(check(lim)) high = lim; else low = lim+1; } printf("%d\n", high); return 0; }