假币之谜
有八个硬币a,b,c,d,e,f,g,h,其中一枚是假币,从外观无法分辨,比真币或轻或重。使用天平,用最少比较次数,找出假币,并分辨出轻重。
#include <iostream>
using namespace std;
int weight(float x, float y) {
if (x == y)return 0;
else if (x > y)return 1;
else return 2;
}
int main(){
float a, b, c, d, e, f, g, h;
cin >> a >> b >> c >> d >> e >> f >> g >> h;
switch (weight(a + b + c, d + e + f)) {
case 0: //a,b,c,d,e,f都是真币
switch (weight(a, g)) {
case 0: //g是真币
if (weight(a, h) == 1)cout << "h是假币,且重量轻";
else cout << "h是假币,且重量重";
break;
case 1: //g是假币
cout << "g是假币,且重量轻";
break;
default:
cout<< "g是假币,且重量重";
}
break;
case 1: //a,b,c与d,e,f中有假币,如果假币重,则在a,b,c中,如果假币轻,则在d,e,f中
switch (weight(a+e+f, d+g+h)) { //a,e,f一组,d,g,h一组
case 0: //b,c是假币
if (weight(a, b) == 0) {
if (weight(a, c) == 1) cout << "c是假币,且重量轻" << endl;
else cout<<" c是假币,且重量重" << endl;
}
else if (weight(a, b)== 1)cout << "b是假币,且重量轻";
else cout << "b是假币,且重量重";
break;
case 1: //a,d是假币
if (weight(a, c) == 1)cout << "a是假币,且重量重" << endl;
else cout << "d是假币,且重量轻" << endl;
break;
default: //e,f是假币
if (weight(c, e) == 1)cout << "e是假币,且重量轻" << endl;
else cout << "f是假币,且重量轻" << endl;
}
break;
case 2: //a,b,c与d,e,f中有假币,如果假币重,则在d,e,f中,如果假币轻,则在a,b,c中
switch (weight(d + b + c, a + h + g)) { //d,b,c一组 a,h,g一组
case 0: //e,f是假币
if (weight(a, e) == 0) {
if (weight(a, f) == 1) cout << "f是假币,且重量轻" << endl;
else cout << " f是假币,且重量重" << endl;
}
else if (weight(a, e) == 1)cout << "e是假币,且重量轻" << endl;
else cout << "e是假币,且重量重"<<endl;
break;
case 1: //d,a是假币
if (weight(d, c) == 1)cout << "d是假币,且重量重" << endl;
else cout << "a是假币,且重量轻" << endl;
break;
default: //b,c是假币
if (weight(a, b) == 1)cout << "b是假币,且重量轻" << endl;
else cout << "c是假币,且重量轻" << endl;
}
}
}