【算法学习】分治法-找硬币的游戏

哎呀,估计是闲得蛋疼,竟然接下了朋友的算法题,呵呵,结果整个就是一打脸,递归,我的痛呀!搞了半天,重新学习了一下分治算法(其中的快速排序),当然今天是以一个例子---找假币的游戏,来说明一下分治算法的原理过程。

废话不多说,直接上代码。(好吧,我已经说了好多废话,不差下面几句了。)

题目:已经有10枚硬币,其中有一枚假币,且假币的质量比真币的要小,求假币的位置?

#include<stdio.h>
#include<conio.h>
#define N 10
 
int FindCorn(int l[],int low,int high)
{  
    int sum1,sum2,i,j=0;
    int length=high-low+1;
    if(length%2==0)
    {
        length=length/2;
	for(i=low,j=low+length;(i<=low+length-1)&&(j<=high);i++,j++)
	{
	  sum1=sum1+l[i];
	  sum2=sum2+l[j];
	}
        if(sum1>sum2){FindCorn(l,low+length,high);}
	else {FindCorn(l,low,low+length-1);}
    }
    else
    {
	length=length/2;
        for(i=low,j=low+length+1;(i<=low+length-1)&&(j<=high);i++,j++)
	{
	  sum1=sum1+l[i];
	  sum2=sum2+l[j];
	}
       if(sum1==sum2) return low+length;
       if(sum1>sum2) {FindCorn(l,low+length+1,high);}
       else{FindCorn(l,low,low+length-1);}
    }
}
 
void main()
{
    int i;
    int corn[N] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 };
    i=FindCorn(corn, 0, N-1);
    printf("假币的位置是%d",i+1);
    getch();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值