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

来源:互联网 发布:应收金额 英文java 编辑:程序博客网 时间:2024/05/16 23:46

分治算法

   一个袋子里有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;}}}