常用算法思想--分治算法

分治算法

   一个袋子里有30个硬币,其中一枚是假币,并且假币和真币一模一样,肉眼难以分辨,目前只知道假币比真币轻。请问如何区分出假币?

  操作步骤如下:

 1、首先为每个银币编号,然后将所有的银币等分为两份,放在天平的两边。这样就将区分30个硬币的问题,变为区别两堆硬币的问题。

 2、因为假币的分量轻,因此天平较轻的一侧中一定包含假币。

 3、在将较轻的一侧中的银币等分为两份,重复上述做法。

 4、知道剩下2枚硬币,可用天平直接找出假币。

int Divide(int *coin, int low,int high)
{
	int i=0,preSum=0,nextSum=0,midSum=0;
	int lightCoin;
	
	if(low+1 == high)
	{
		if(coin[low] < coin[high])
		{
			lightCoin = low+1;
			return lightCoin;
		}
		else
		{
			lightCoin = high+1;
			return lightCoin;
		}
	}

	if((high - low +1)%2 == 0) //偶数
	{
		for(i = low;i<=low+(high+low)/2;i++)
		{
			preSum = preSum+coin[i];
		}

		for(i = low+(high+low)/2;i<=high;i++)
		{
			nextSum = nextSum+coin[i];
		}
		if(preSum > nextSum)
		{
			lightCoin = Divide(coin,low+(low+high)/2,high);
			return lightCoin;
		}
		else if((preSum < nextSum)
		{
			lightCoin = Divide(coin,low,low+(low+high)/2);
			return lightCoin;
		}
		else
		{
		}
	}
	else
	{
		for(i = low;i<=low+(high+low)/2;i++)
		{
			preSum = preSum+coin[i];
		}

		for(i = low+(high+low)/2;i<=high;i++)
		{
			nextSum = nextSum+coin[i];
		}
		midSum = coin[low+(low+high)/2];

		if(preSum > nextSum)
		{
			lightCoin = Divide(coin,low+(low+high)/2,high);
			return lightCoin;
		}
		else if((preSum < nextSum)
		{
			lightCoin = Divide(coin,low,low+(low+high)/2);
			return lightCoin;
		}
		else
		{
		}
		if(preSum + midSum == nextSum + midSum)
		{
			lightCoin = low+(low+high)/2 + 1;
			return lightCoin;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值