八硬币问题

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");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值