第二题:
#include <iostream>
#include<vector>
using namespace std;
int Judge(vector<int>&data, int mid, int m, int n)
{
int cnt = 0;
int sum = 0;
for (int i = 0; i < n; i++)
{
if (sum + data[i] > mid)
{
sum = data[i];
cnt++;
if (cnt > m - 1)
{
return 0;
}
}
else
{
sum += data[i];
}
}
return 1;
}
int Binary_Search(vector<int>&data, int left, int right, int m, int n)
{
int mid = 0;
while (left < right)
{
mid = left + (right - left) / 2;
if (Judge(data, mid, m, n))
{
right = mid;
}
else //
{
left = mid + 1;
}
}
return left;
}
int main()
{
int n = 0, m = 0;
cin >> n >> m;
vector<int> data(n,0);
int max_num = 0;
int sum = 0;
int i = 0;
for (i = 0; i < n; i++)
{
cin >> data[i];
if (data[i] > max_num)
{
max_num = data[i];
}
sum += data[i];
}
cout << Binary_Search(data, max_num, sum, m, n);
return 0;
}