枚举算法的二分法

题目描述:
有 N 条绳子,它们的长度分别为 L i L_i Li。如果从它们中切割出 K 条长度相同的绳子,这 K 条绳子每条最长能有多长?答案保留到小数点后 2 位。

代码:



#include <stdio.h>

#include <windows.h>

#include <vector>


#include <conio.h>


using namespace std;


int sort(double ropes[],int rope_num)
{

	for (int i = rope_num-1;i >= 0;i --)
	{
		for (int j = 0;j < i;j ++)
		{
			if (ropes[j+1] < ropes[j])
			{
				double tmp = ropes[j+1];
				ropes[j+1] = ropes[j];
				ropes[j] = tmp;
			}
		}
	}
	return 0;
}



int split(double  ropes[], int rope_num,int len, int cnt) {

	int total = 0;
	for (int i = 0;i < rope_num;i ++)
	{
		total += ropes[i] / len;
	}
	return total;
}

double makeRope(double  ropes[],int rope_num,int cnt) {

	if (rope_num >= cnt)
	{
		return FALSE;
	}

	double min = 0;

	double max = ropes[rope_num - 1];

	double mid = (min + max) / 2;

	while (  max - min > 0.01)
	{
		mid = (min + max) /2;

		int total = split(ropes, rope_num, mid, cnt);
		if (total < cnt)
		{

			max = mid;

		}else if (total > cnt)
		{
			min = mid;
		}
		else {
			//break;
			min = mid;
		}
	}
	return mid;
}


int main(int argc,char ** argv) {


	double ropes1[8] = { 3.2,1.5,10.8,1024,66.66,888.88,9.1,6.2 };

	double ropes2[8] = { 13.2,21.5,102.8,104,666.66,188.88 ,1402.12,10004.6};

	sort(ropes1,sizeof(ropes1) / sizeof(ropes1[0]));

	sort(ropes2, sizeof(ropes2) / sizeof(ropes2[0]));

	double maxlong1 = makeRope(ropes1, sizeof(ropes1)/sizeof(ropes1[0]), 13);

	printf("rope1 max long :%lf\r\n", maxlong1);

	double maxlong2 = makeRope(ropes2, sizeof(ropes2) / sizeof(ropes2[0]), 18);

	printf("rope2 max long :%lf\r\n", maxlong2);
	_getch();

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值