package com.xj.www.algo;
import java.util.Scanner;
/**
* 分治算法
*
* @author xiongjing
*
*/
public class DivideTest {
static int FalseCoin(int coin[], int low, int high) {
int i, sum1, sum2, sum3;
int re = 0;
sum1 = sum2 = sum3 = 0;
// 算法具体实现
// 判断high == 1的情况
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 += coin[i];
}
for (i = low + (high - low) / 2 + 1; i <= high; i++) {
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 += coin[i];
}
for (i = low + (high - low) / 2 + 1; i <= high; i++) {
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);
} else {
}
if (sum1 + sum3 == sum2 + sum3) {
re = low + (high - low) / 2 + 1;
return re;
}
}
return re;
}
// 方法主入口
public static void main(String[] args) {
int i, n;
int weizhi;
System.out.println("分治算法求解假币问题!");
System.out.print("请输入硬币总的个数:");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.print("请输入硬币的真假:");
int[] coin = new int[n];
for (i = 0; i < n; i++) {
coin[i] = sc.nextInt();
}
weizhi = FalseCoin(coin, 0, n - 1);
System.out.println("在上述" + n + "个硬币中,第" + weizhi + "个硬币是假的!");
}
}
分治算法
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+...