poj 3273 Monthly Expense

给出一组数据,最大值为left,和为right。在[left,right]区间进行二分!!!

代码:

 

 1 #include<iostream>

 2 #include<stdio.h>

 3 #include<algorithm>

 4 #include<iomanip>

 5 #include<cmath>

 6 #include<cstring>

 7 #include<vector>

 8 #define ll __int64

 9 #define pi acos(-1.0)

10 #define MAX 50000

11 using namespace std;

12 int an[100005];

13 int main(){

14     int n,m,i,sum,left,right=0,mid,t;

15     while(cin>>n>>m){

16         for (i=0;i<n;i++){

17             cin>>an[i];

18             if(i){

19                 if(left<an[i]) left = an[i];

20             }else{

21                 left = an[i];

22             }

23             right += an[i];

24         }

25         while (left<right){

26             mid = (left+right)/2;

27             sum = 0;t = 0;

28             for (i=0;i<n;i++){

29                 if (sum+an[i]>mid){//如果大于mid则区间短+1

30                     sum = an[i];

31                     t++;

32                 }

33                 else {

34                     sum += an[i];

35                 }

36             }

37             if (t<m){//t<m,说明m取大了

38                 right = mid;

39             }

40             else{

41                 left = mid+1;

42             }

43         }

44         cout<<right<<endl;

45     }

46     return 0;

47 }
View Code

 

 

 

你可能感兴趣的:(exp)