POJ 1064 Cable master (二分答案)

#include <stdio.h>
#define MAX_CABLES 10000
#define MAX_LENGTH 1e5

int numOfCables, numOfPieces;
int lengthArray[MAX_CABLES + 1];

int main(){
	scanf("%d%d", &numOfCables, &numOfPieces);
	int cable;
	int right = 0;
	for (cable = 1; cable <= numOfCables; cable++){
		double length;
		scanf("%lf", &length);
		//扩大精度
		lengthArray[cable] = length * 100;
		if (lengthArray[cable] > right)
			right = lengthArray[cable];
	}

	int maxLength = 0;
	//从区间[1, 最大的cable长度]开始二分答案
	int left = 1;
	while (left <= right){
		int mid = (left + right) >> 1;
		int pieces = 0;
		for (cable = 1; cable <= numOfCables; cable++){
			pieces += lengthArray[cable] / mid;
			if (pieces >= numOfPieces)
				break;
		}
		if (pieces >= numOfPieces){
			maxLength = mid;
			left = mid + 1;
		} else
			right = mid - 1;;
	}

	//输出要还原精度
	printf("%.2f\n", (double)maxLength/100.0);

	return 0;
}

你可能感兴趣的:(master,poj,二分,1064,CABLE,二分答案)