https://loj.ac/problem/10014
题解:这类题显然考虑二分答案,然后贪心一下就好了
错误:注意l和r的范围,l的范围一定是要大等于每个数的,不然就会出错!!!
代码
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; int a[1010011],m,n; int s(int x){ int sum=0,ans=1; for(int i=1;i<=n;i++){ if(x<sum+a[i]&&x>=a[i])//wrong sum=a[i],ans++; else sum+=a[i]; if(ans>m)return false; } return true; } int main(){ int l=1,r=0; // freopen("a.in","r",stdin); // freopen("a.out","w",stdout); scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]),r+=a[i]; int ans; while(l<=r){ int mid=(l+r)/2; if(s(mid))ans=mid,r=mid-1; else l=mid+1; } printf("%d",ans); return 0; }