分治算法
分治算法的基本思想是将一个计算复杂的问题分为规模较小、计算简单的小问题求解,然后综合各个小问题,得到最终问题的答案。分治算法的执行过程:
1. 对于一个规模为N的问题,若该问题比较容易解决,则直接解决:否则执行下面的步骤。
2. 将该问题分解为M个规模较小的子问题,这些问题互相独立,并且与原问题形式相同。
3. 递归地解这些子问题。
4. 然后,将各子问题的解合并得到原问题的解。
实例:
一个袋子里有30个硬币,其中一枚是假币,并且假币和真币一模一样,看不出来。只知道假币比真币轻。怎么才能找到假币?
算法解析
1. 首先为每个硬币编号,然后将所有的硬币等分为两份,放在天平的两边。这样就将硬币问题变为区别两堆硬币的问题。
2. 因为假币的重量较轻,因此天平较轻的一侧中一定包含假币。
3. 再将较轻的一侧中的硬币等分为两份,重复上面的做法。
4. 直到剩下两枚硬币,可用天平直接找出假币。
public class P3_4 {
static final int MAXNUM = 30;
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){ // n 是偶数
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+(high-low)/2+1,high);
return re;
}else if(sum1<sum2){
re = FalseCoin(coin,low,low+(high-low)/2);
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 re;
}
}