题目描述 Description
果园里有n颗果树,每棵果树都有一个编号i(1≤i≤n)。小明已经把每棵果树上的果子都摘下来堆在了这棵树的下方,每棵树下方的果子体积为ai。
现在小明将拿来m个袋子把这些果子都装进袋子里。每个袋子的体积为v。小明会按照如下规则把果子装进袋子里:
(a)从第1棵果树开始装起,由1到n一直装到第n棵果树。
(b)如果这棵果树下的果子能全部装进当前这个袋子,就装进去;如果不能,就关上当前这个袋子,打开一个新的袋子开始装。
输入描述 Input Description
输入第1行,包含两个整数n和m。
第2行,包含n个整数ai。
输出描述 Output Description
输出仅1行,表示最小的v。
#include<iostream>
#include<cstdio>
#define LL long long
using namespace std;
const int MAXN = 200000 + 5;
LL a[MAXN],v,n,m,maxx,max1;
bool check(LL x)
{
LL cnt = 1,now = 0;
for(int i = 1;i <= n;i ++)
{
if(now + a[i] <= x)
{
now += a[i];
}
else
{
if(a[i] > x)return false;
cnt ++;
now = a[i];
if(cnt > m)return false;
}
}
return true;
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i ++)
{
cin >> a[i];
maxx += a[i];
max1 = max(max1,a[i]);
}
LL l = max1 - 1,r = maxx + 1;
while(r - l > 1)
{
LL mid = l + r >> 1;
if(check(mid))r = mid;
else l = mid;
}
cout << r;
}
二分时注意边界
看清数据范围
long long!