POJ-3273 Monthly Expense---最小化最大值
题目链接:
https://cn.vjudge.net/problem/POJ-3273
题目大意:
给N个数,划分为M个块(不得打乱数顺序)。找到一个最好的划分方式,使得块的和的最大值 最小
解题思路:
首先是最大值最小
写出二分模板(需要确定上下界)
然后根据二分模板写chack函数
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 typedef long long ll; 5 const int maxn = 1e6 + 10; 6 int n, m; 7 int a[maxn]; 8 bool judge(int x) 9 { 10 int tot = 0, cnt = 1; 11 for(int i = 1; i <= n; i++) 12 { 13 if(tot + a[i] > x) 14 { 15 tot = a[i]; 16 cnt++; 17 } 18 else tot += a[i]; 19 } 20 //cout<<x<<":::"<<cnt<<endl; 21 return cnt <= m; 22 } 23 int main() 24 { 25 while(cin >> n >> m){ 26 int l = 0, r = 0, ans; 27 for(int i = 1; i <= n; i++) 28 scanf("%d", &a[i]), r += a[i], l = max(l, a[i]); 29 //l 和 r的范围必须确定好 30 31 while(l <= r) 32 { 33 int mid = (l + r) / 2; 34 if(judge(mid)) 35 ans = mid, r = mid - 1; 36 else l = mid + 1; 37 } 38 cout<<ans<<endl; 39 } 40 return 0; 41 }
越努力,越幸运