POJ 3273 Monthly Expense (二分答案)

#include <stdio.h>
#define MAX_DAYS 100000
int numOfDays, numOfPeriods;
int dollersArray[MAX_DAYS + 1];

int main(){

	scanf("%d%d", &numOfDays, &numOfPeriods);

	int minLimit = 0;
	int maxLimit = 0;
	int day;
	for (day = 1; day <= numOfDays; day++){
		int dollers;
		scanf("%d", &dollers);
		maxLimit += dollers;
		if (dollers > minLimit)
			minLimit = dollers;
		dollersArray[day] = dollers;
	}
	int result = 1e10;
	int midLimit;
	//从区间[最小的每天预算,预算总和]开始二分搜索答案
	while (minLimit <= maxLimit){
        midLimit = minLimit + ( (maxLimit - minLimit) >> 1);
		int periods = 1;
		int sum = 0;
		int tooSmall = 0;
		for (day = 1; day <= numOfDays; day++){
			if (sum + dollersArray[day] <= midLimit)
				sum += dollersArray[day];
			else {
				sum = dollersArray[day];
				periods++;
				//注意判断条件
				if (periods > numOfPeriods || dollersArray[day] > midLimit){
					tooSmall = 1;
					break;
				}
			}
		}
		if (tooSmall == 1)
			minLimit = midLimit + 1;
		else {
			result = midLimit;
			maxLimit = midLimit - 1;
		}
		
	}

	printf("%d\n", result);

	return 0;
}


 
 
 

你可能感兴趣的:(poj,二分,monthly,二分答案,3273,Expense)