题意:将N个账款分给城M个财务期,使得每个分期账款和的值最大?
思路:
- 每次mid为分期账款
- 如果分期次数小于m说明mid太大,减上限 反正 增下限
- 开始下限设为 最大值 上限设为和
解决问题的代码:
#include<iostream> #include<cstdio> #include<cstring> #include <algorithm> using namespace std; int n, m; int a[100005]; bool Judge(int mid) { int sum = 0, num = 1;//查询每组上限为mid的情况下的组数 for (int i = 1; i <= n; i++) { if (sum + a[i] <= mid) sum += a[i]; else { sum = a[i]; num++; } } if (num > m)//组数偏大,说明mid偏小 return true; else return false; } int main() { cin >> n >> m; int maxn = -1, sum = 0; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); maxn = max(maxn, a[i]); sum += a[i]; } int low = maxn, high = sum; int mid = (low + high) / 2; while (low < high) { if (Judge(mid)) low = mid + 1; else high = mid - 1; mid = (low + high) / 2; } printf("%d ", mid); return 0; }