Ss 八硬币问题(读者自己根据tips先写程序在看我的代码哈^_^)
1两两分组称;
2注意互补情况下可以省略某些称量步骤,减少称量次数
3求解的是总共比较次数,欲知与决策树的效率问题,且看下篇博文——“八硬币问题之比较”
Ps 也用决策树解决!!!
#include<iostream>
using namespace std;
int a[8];
int cmptimes = 0;
void FindFake(){ //should differ the weight of two kinds of coins
cmptimes += 1;//a[0] compared to a[1]
if (a[0] != a[1]){// at this time a[2] is real coin
cmptimes++;//a[0] compared to a[2]
if (a[0] == a[2]){
cmptimes++;//a[1] compared to a[2] differ the weight;have done it all
}
if (a[0] != a[2]);// have done it all
return;
}
for (int i = 2; i <=4; i+=2){//a[0]==a[1],they are real
cmptimes++;
if (a[i] != a[i+1]){// at this time a[0] is real coin
cmptimes++;//a[i] compared to a[0]
if (a[i] == a[0]){
cmptimes++;//a[i+1] compared to a[0] differ the weight;have done it all
}
if (a[i] != a[0]);// have done it all
return;
}
}
//when the former pairs is all real,the fake is in the last pair
//so no need to weigh the last pair
//if (a[6] != a[7]){// at this time a[0] is real coin
cmptimes++;//a[6] compared to a[0]
if (a[6] == a[0]){
cmptimes++;//a[7] compared to a[0] differ the weight;have done it all
}
if (a[6] != a[0]);// have done it all
return;
//}
}
int main(){
int fakeweighmore=1;//fake coin weigh more
for (int fake = 0; fake < 8; fake++){
a[fake] += fakeweighmore;
FindFake();
a[fake] -= fakeweighmore;
}
cmptimes *= 2;//it's also applied to the case when the fake is light
//fakeweighmore = -1;
//for (int fake = 0; fake < 8; fake++){
// a[fake] += fakeweighmore;
// FindFake();
// a[fake] -= fakeweighmore;
//}
cout << cmptimes << endl;
system("pause");
}