蓝桥杯:2017年第八届蓝桥杯省赛B组第九题—PREV-37分巧克力

在 1~100000 之间查找满足分巧克力要求的的最大解,线性查找用二分法。

while(left<=right)
{
    int temp=(left+right)/2;
    if(check(K,N,temp))
	left=temp+1;
    else
	right=temp-1;
}

由于不是查找指定值,因此需要错开平均值来结束程序。结束二分查找后最大值可能是两个数,left 和 left-1 。这是因为最后一次判断平均值可能是成功的,然后 left = temp + 1 后结束,这种情况最大值是 left - 1 ;同理如果最后一次判断是失败的,那么循环是因为 right=temp-1 而终止,left 就是最大值。

#include<stdio.h>
#include<stdlib.h>
#define arrmax 100000+1
int Narray[arrmax],Karray[arrmax];
int check(int key,int N,int temp)
{
	int i,sum=0;
	for(i=1;i<=N;i++)
		sum+=(Narray[i]/temp)*(Karray[i]/temp);
	if(sum>=key)
		return 1;
	return 0;
}
int main(int argc,char **argv)
{
	int N,K;
	scanf("%d%d",&N,&K);
	int i;
	for(i=1;i<=N;i++)
		scanf("%d%d",&Narray[i],&Karray[i]);
	int left=1,right=arrmax-1;
	while(left<=right)
	{
		int temp=(left+right)/2;
		if(check(K,N,temp))
			left=temp+1;
		else
			right=temp-1;
	}
	if(check(K,N,left-1))
		left--;
	printf("%d\n",left);
	return EXIT_SUCCESS;	
} 

 

END

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值