分治算法寻找硬币

来源:互联网 发布:ps软件电脑版 编辑:程序博客网 时间:2024/06/07 15:26

1,寻找假硬币

2,步骤:1 首先为每个硬币编号,然后可以将所有的硬币等分为两份,放在天平的两端;

            2 因为假硬币分量比较轻,因此天平较轻的一端一定包含假硬币

            3 再将较轻的一侧中的硬币等分为两部分,重述上方的做法。,

3,伪代码如下:

public static int FalseCoin(int coin[],int low,int high){
int i,sum1,sum2,sum3;
int re = 0;
sum1=sum2=sum3=0;
if(low+1==high){
if(coin[low]<coin[high]){
re = low+1;
return re;
}
else{
re = high+1;
return re;
}
}

if((high-low+1)%2 == 0){

for(i=low;i<=low+(high-low)/2;i++){
sum1 = sum1+coin[i];
}
for(i=low+(high-low)/2+1;i<=high;i++){
sum2=sum2+coin[i];
}
if(sum1<sum2){
re = FalseCoin(coin, low, low+(high-low)/2);
return re;
}
else if(sum1>sum2){
re = FalseCoin(coin, low+(high-low)/2, high);
return re;
}
else{

}
}
else{
for(i=low;i<=low+(high-low)/2-1;i++){
sum1 = sum1+coin[i];
}
for(i = low+(high-low)/2+1;i<=high;i++){
sum2=sum2+coin[i];
}
sum3 = coin[low+(high-low)/2];
if(sum1>sum2){
re = FalseCoin(coin, low+(high-low)/2+1, high);
return re;
}
else if(sum1<sum2){
re = FalseCoin(coin, low, low+(high-low)/2-1);
return re;
}
else{

}
if(sum1+sum3==sum2+sum3){
re = low+(high-low)/2+1;
return re;
}
}
return 0;

}



0 0
原创粉丝点击