问题:已知n个球(n>2)中有一个重量跟别的球不一样,但不知道它是轻还是重。
用一架天平最少称多少次能找出这个次品?输出最少次数及称球方案
已知小球个数,用数学方法可推导出最少次数,但无法推导出所有的最佳称球方案。要做到这一点唯有代码实现。
思路:
随着称重和推导进行,对于小球集合的了解增加,在某一时刻,对小球集合所积累的知识可以量化表现为四个参数:正常小球个数、不明小球个数、疑似重球个数、疑似轻球个数。可以将它们封装为一个对象,取名为Status。
每一次称重的行为也可量化表现为8个参数,即天平左右两边四种球的个数,可将它们封装为一个对象,取名为Balance。
整个求解过程实际上就是一个求解树的构建过程,树的节点为Status或Balance对象。
求解树包括以下规律:
1) 根节点为初始Status
2) 每个Status对象的子节点都为Balance对象,含义是对此Status所有可能的称球方案
3) 每个Balance对象的子节点都为Status对象,含义是此次称重可能产生的三个结果(天平两边一样重、左边重、右边重)
求解过程:
若某个Status对象中只包括1个疑似重球或轻球或不明小球,称此Status为可解决的。若Status的正常小球数等于初始小球总数n,称此Status为不可能的。在此前提下,若一个Balance对象的3个Status子节点都是可解决的或不可能的,称此Balance对象为可解决的。若一个Status对象的某一个Balance子节点为可解决的,该Status继承可解决属性。
以广度优先的原则构建此求解树,每生成一个树的新节点,都根据新节点的可解决属性进行回溯逆推,直到根节点成为可解决的,则求解成功。
如欲求出所有最少称球次数解,则在找到第一个解后,继续完成同层的求解树构建,可求得所有最优解。
优化:
构造求解树是最朴素直观的求解过程。在求解树中的不同的分支及不同的层中可能出现完全相同的Status对象,将它们归并可大大提高算法的时间效率和减少内存占用,此时求解树变为一个图结构,在推导结束后采用图最小路径查找算法可得到最优解。此优化将导致求解过程的时间复杂度和内存使用收敛于O(n^3)
以下为代码演示实现,演示代码在找到第一个最优解后结束,且未做进一步的优化。总计约200行,预计加上优化300行。
packagebalance;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Scanner;
publicclassWeightBall {
staticintround =1;
staticintmaxSteps;
publicstaticvoidrun(Status root, List list) {//求解
longtime = System.currentTimeMillis();
List newlist =newArrayList();
for(inti=0; i
Status status = list.get(i);
status.produceBalances();
for(intj=0; j
Balance bl = status.bls.get(j);
bl.weight();
if(root.succeed()) {
System.out.println("第"+ round +"轮: 计算至上轮第"+ (i+1) +"个节点得解,之前获得节点"+ newlist.size() +"个,用时"+ (double)(System.currentTimeMillis()-time)/1000+"秒");return;
}
if(bl.out1.isUnknown()) newlist.add(bl.out1);
if(bl.out2.isUnknown()) newlist.add(bl.out2);
if(bl.out3.isUnknown()) newlist.add(bl.out3);
}
}
System.out.println("第"+ round +"轮: 获得节点"+ newlist.size() +"个,用时"+ (double)(System.currentTimeMillis()-time)/1000+"秒");
round++;
run(root, newlist);
}
publicstaticvoidprint(Status st,intdepth) {//输出结果
String indent="";
for(inti=0; i
Balance bl=null;
for(inti=0; i
if(st.bls.get(i).unresolved==0) bl=st.bls.get(i);
if(bl!=null) {
if(depth>maxSteps) maxSteps=depth;
System.out.println(indent +"第"+ depth +"步称重: "+ bl +"\r\n");
System.out.println(indent +"如果一样重: "+ bl.out1 + (bl.out1.getConclusion()==Status.RESOLVED?" *解决*":(bl.out1.getConclusion()==Status.REDICULOUS?" ×不可能×":"")) +"\r\n");
print(bl.out1, depth+1);
System.out.println(indent +"如果左边重: "+ bl.out2 + (bl.out2.getConclusion()==Status.RESOLVED?" *解决*":(bl.out2.getConclusion()==Status.REDICULOUS?" ×不可能×":"")) +"\r\n");
print(bl.out2, depth+1);
System.out.println(indent +"如果右边重: "+ bl.out3 + (bl.out3.getConclusion()==Status.RESOLVED?" *解决*":(bl.out3.getConclusion()==Status.REDICULOUS?" ×不可能×":"")) +"\r\n");
print(bl.out3, depth+1);
}
}
publicstaticvoidmain(String[] args) {
Scanner sc =newScanner(System.in);
System.out.println("请输入小球个数(大于2,超过14请调整JVM内存):");
intn = sc.nextInt();
Status root =newStatus(n);
ArrayList list =newArrayList();
list.add(root);
System.out.println("***** 开始求解......");
run(root, list);
System.out.println("\r\n***** 步骤说明:");
maxSteps =0;
print(root,1);
System.out.println("\r\n***** 总计"+ maxSteps +"步可解!");
}
}
package balance;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class WeightBall {
static int round = 1;
static int maxSteps;
public static void run(Status root, List list) { //求解
long time = System.currentTimeMillis();
List newlist = new ArrayList();
for (int i=0; i
Status status = list.get(i);
status.produceBalances();
for (int j=0; j
Balance bl = status.bls.get(j);
bl.weight();
if (root.succeed()) {
System.out.println("第" + round + "轮: 计算至上轮第" + (i+1) + "个节点得解,之前获得节点" + newlist.size() + "个,用时" + (double)(System.currentTimeMillis()-time)/1000 + "秒");return;
}
if (bl.out1.isUnknown()) newlist.add(bl.out1);
if (bl.out2.isUnknown()) newlist.add(bl.out2);
if (bl.out3.isUnknown()) newlist.add(bl.out3);
}
}
System.out.println("第" + round + "轮: 获得节点" + newlist.size() + "个,用时" + (double)(System.currentTimeMillis()-time)/1000 + "秒");
round++;
run(root, newlist);
}
public static void print(Status st, int depth) { //输出结果
String indent="";
for (int i=0; i
Balance bl=null;
for (int i=0; i
if (st.bls.get(i).unresolved==0) bl=st.bls.get(i);
if (bl!=null) {
if (depth>maxSteps) maxSteps=depth;
System.out.println(indent + "第" + depth + "步称重: " + bl + "\r\n");
System.out.println(indent + "如果一样重: " + bl.out1 + (bl.out1.getConclusion()==Status.RESOLVED?" *解决*":(bl.out1.getConclusion()==Status.REDICULOUS?" ×不可能×":"")) + "\r\n");
print(bl.out1, depth+1);
System.out.println(indent + "如果左边重: " + bl.out2 + (bl.out2.getConclusion()==Status.RESOLVED?" *解决*":(bl.out2.getConclusion()==Status.REDICULOUS?" ×不可能×":"")) + "\r\n");
print(bl.out2, depth+1);
System.out.println(indent + "如果右边重: " + bl.out3 + (bl.out3.getConclusion()==Status.RESOLVED?" *解决*":(bl.out3.getConclusion()==Status.REDICULOUS?" ×不可能×":"")) + "\r\n");
print(bl.out3, depth+1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入小球个数(大于2,超过14请调整JVM内存):");
int n = sc.nextInt();
Status root = new Status(n);
ArrayList list = new ArrayList();
list.add(root);
System.out.println("***** 开始求解......");
run(root, list);
System.out.println("\r\n***** 步骤说明:");
maxSteps = 0;
print(root, 1);
System.out.println("\r\n***** 总计" + maxSteps + "步可解!");
}
}
packagebalance;
importjava.util.ArrayList;
importjava.util.List;
publicclassStatus {
publicstaticintRESOLVED=1, UNKNOWN=2, REDICULOUS=3, RESOLVABLE=4;
publicintcount=0;
publicint[] data;
publicList parents =newArrayList();
publicList bls =newArrayList();
privateintconclusion;
publicStatus(intc) {
count = c;
int[] data1 = {0,c,0,0};
data = data1;
intconc = data[0]
setConclusion(conc);
}
publicStatus(int[] is) {
data = is;
for(inti=0; i
intconc = data[0]
setConclusion(conc);
}
publicvoidaddParent(Balance bl) {
parents.add(bl);
if(conclusion==RESOLVED || conclusion==RESOLVABLE || conclusion==REDICULOUS) bl.prop();
}
publicString toString() {
return"正常"+ data[0] +"、不明"+ data[1] +"、或重"+ data[2] +"、或轻"+ data[3];
}
publicvoidsetConclusion(intconc) {
if(conclusion == conc)return;
conclusion = conc;
if(conclusion==RESOLVED || conclusion==RESOLVABLE || conclusion==REDICULOUS)
for(inti=0; i
parents.get(i).prop();
}
publicintgetConclusion() {returnconclusion;}
publicbooleansucceed() {returnconclusion==RESOLVED || conclusion==RESOLVABLE;}
publicbooleanisUnknown(){returnconclusion==UNKNOWN;}
publicvoidproduceBalances() {//得到当前状况下所有可能的称重方案
List bldata = getBalanceDataArray(data);
bls =newArrayList();
for(inti=0; i
Balance bl =newBalance(bldata.get(i));
bl.in =this;
bls.add(bl);
}
}
privateList getBalanceDataArray(int[] src) {
List list =newArrayList();
list.add(newint[src.length*2]);
returngetBalanceDataArray(src,0,list);
}
privateList getBalanceDataArray(int[] src,intid, List list) {
inttotal=0,left,right;
if(id>=src.length) {
for(inti=list.size()-1; i>=0; i--) {
int[] is = list.get(i);
left=0;
right=0;
for(intj=0; j
for(intj=src.length; j
if(left!=right || left==0|| is[0]>0&&is[is.length/2]>0)
list.remove(i);
}
returnlist;
}
List r =newArrayList();
for(inti=0; i
inthalf = total/2;
for(inti=0; i
int[] is = list.get(i);
left=0;
right=0;
for(intj=0; j
for(intj=src.length; j
for(intj=0; j<=Math.min(half-left, src[id]); j++) {
for(intk=0; k<=Math.min(half-right, src[id]-j); k++) {
int[] iis = list.get(i).clone();
iis[id] = j;
iis[id+src.length] = k;
r.add(iis);
}
}
}
returngetBalanceDataArray(src,id+1,r);
}
}
package balance;
import java.util.ArrayList;
import java.util.List;
public class Status {
public static int RESOLVED=1, UNKNOWN=2, REDICULOUS=3, RESOLVABLE=4;
public int count=0;
public int[] data;
public List parents = new ArrayList();
public List bls = new ArrayList();
private int conclusion;
public Status(int c) {
count = c;
int[] data1 = {0,c,0,0};
data = data1;
int conc = data[0]
setConclusion(conc);
}
public Status(int[] is) {
data = is;
for (int i=0; i
int conc = data[0]
setConclusion(conc);
}
public void addParent(Balance bl) {
parents.add(bl);
if (conclusion==RESOLVED || conclusion==RESOLVABLE || conclusion==REDICULOUS) bl.prop();
}
public String toString() {
return "正常" + data[0] + "、不明" + data[1] + "、或重" + data[2] + "、或轻" + data[3];
}
public void setConclusion(int conc) {
if (conclusion == conc) return;
conclusion = conc;
if (conclusion==RESOLVED || conclusion==RESOLVABLE || conclusion==REDICULOUS)
for (int i=0; i
parents.get(i).prop();
}
public int getConclusion() {return conclusion;}
public boolean succeed() {return conclusion==RESOLVED || conclusion==RESOLVABLE;}
public boolean isUnknown(){return conclusion==UNKNOWN;}
public void produceBalances() {//得到当前状况下所有可能的称重方案
List bldata = getBalanceDataArray(data);
bls = new ArrayList();
for (int i=0; i
Balance bl = new Balance(bldata.get(i));
bl.in = this;
bls.add(bl);
}
}
private List getBalanceDataArray(int[] src) {
List list = new ArrayList();
list.add(new int[src.length*2]);
return getBalanceDataArray(src,0,list);
}
private List getBalanceDataArray(int[] src, int id, List list) {
int total=0,left,right;
if (id>=src.length) {
for (int i=list.size()-1; i>=0; i--) {
int[] is = list.get(i);
left=0;
right=0;
for (int j=0; j
for (int j=src.length; j
if (left!=right || left==0 || is[0]>0&&is[is.length/2]>0)
list.remove(i);
}
return list;
}
List r = new ArrayList();
for (int i=0; i
int half = total/2;
for (int i=0; i
int[] is = list.get(i);
left=0;
right=0;
for (int j=0; j
for (int j=src.length; j
for (int j=0; j<=Math.min(half-left, src[id]); j++) {
for (int k=0; k<=Math.min(half-right, src[id]-j); k++) {
int[] iis = list.get(i).clone();
iis[id] = j;
iis[id+src.length] = k;
r.add(iis);
}
}
}
return getBalanceDataArray(src,id+1,r);
}
}
packagebalance;
publicclassBalance {
publicint[] data;
publicStatus in,out1,out2,out3;
publicintunresolved =3;
publicBalance(int[] data) {
this.data = data.clone();
}
publicvoidweight() {//称重量,推理出三种可能的结果
int[] temp;
// 一样重
temp = in.data.clone();
for(inti=1; i<4; i++) {//所有参与称重的球都移入正常球集合
temp[0] = temp[0] + data[i] + data[i+4];
temp[i] = temp[i] - data[i] - data[i+4];
}
out1 =newStatus(temp);
out1.addParent(this);
//左边重
temp = in.data.clone();
for(inti=1; i<4; i++) {
temp[0] = temp[0] + temp[i] - data[i] - data[i+4];//未参与称重的球 -->> 正常球
}
temp[0] += data[3] + data[6];//左边的疑似轻球、右边的疑似重球 -->> 正常球
temp[1] =0;
temp[2] = data[1] + data[2];//左边的不明轻重球移入疑似重球集合
temp[3] = data[5] + data[7];//右边的不明轻重球移入疑似轻球集合
out2 =newStatus(temp);
out2.addParent(this);
//右边重
temp = in.data.clone();
for(inti=1; i<4; i++) {
temp[0] = temp[0] + temp[i] - data[i] - data[i+4];//未参与称重的球 -->> 正常球
}
temp[0] += data[2] + data[7];//左边的疑似重球、右边的疑似轻球 -->> 正常球
temp[1] =0;
temp[2] = data[5] + data[6];//右边的不明轻重球移入疑似重球集合
temp[3] = data[1] + data[3];//左边的不明轻重球移入疑似轻球集合
out3 =newStatus(temp);
out3.addParent(this);
}
publicString toString(){
return"("+ (data[0]>0?"正常球×"+data[0]+"个 ":"") + (data[1]>0?"不明球×"+data[1]+"个 ":"")
+(data[2]>0?"疑似重球×"+data[2]+"个 ":"") + (data[3]>0?"疑似轻球×"+data[3]+"个 ":"")
+") --天平-- ("
+ (data[4]>0?"正常球×"+data[4]+"个 ":"") + (data[5]>0?"不明球×"+data[5]+"个 ":"")
+(data[6]>0?"疑似重球×"+data[6]+"个 ":"") + (data[7]>0?"疑似轻球×"+data[7]+"个 ":"") +")";
}
publicvoidprop() {
if(unresolved <=0)return;
unresolved--;
if(unresolved ==0) in.setConclusion(Status.RESOLVABLE);
}
}