1.题目
描述Happily, Sally has a friend who loans her a very accurate balance scale. The friend will permit Sally three weighings to find the counterfeit coin. For instance, if Sally weighs two coins against each other and the scales balance then she knows these two coins are true. Now if Sally weighs
one of the true coins against a third coin and the scales do not balance then Sally knows the third coin is counterfeit and she can tell whether it is light or heavy depending on whether the balance on which it is placed goes up or down, respectively.
By choosing her weighings carefully, Sally is able to ensure that she will find the counterfeit coin with exactly three weighings.
1 ABCD EFGH even ABCI EFJK up ABIJ EFGH even
K is the counterfeit coin and it is light.
2.解法
题目大意是说有12枚硬币,其中有一枚假币,称三次找出假币并判断假币轻还是重。对于结果是even(平)的,两边肯定都是真币,对于天平右边是“up”或者“down”的,重的那边所有币重量加,轻的那边所有币重量减。最后比较那个币的绝对值重量最大即可找出来假币(真币就不用比较了)。
#include <cstdio>
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
int abs(int a) {
return a >= 0 ? a:-a;
}
int main(int argc, char const **argv) {
int n;
//freopen("C:\\Users\\15321\\Desktop\\code\\test.txt", "r", stdin);
cin >> n;
string left, right, result;
int realCoin[20], temp[20];
while(n--) {
memset(realCoin, 0, sizeof(realCoin));
memset(temp, 0, sizeof(temp));
for(int i = 0; i < 3; i++) {
cin >> left >> right >> result;
if(result == "even") {
for(int j = 0; left[j]; j++) {
realCoin[left[j]-'A'] = 1;
}
for(int j = 0; right[j]; j++) {
realCoin[right[j]-'A'] = 1;
}
}
if(result == "up") {
for(int j = 0; left[j]; j++) {
temp[left[j]-'A']++;
}
for(int j = 0; right[j]; j++) {
temp[right[j]-'A']--;
}
}
if(result == "down") {
for(int j = 0; left[j]; j++) {
temp[left[j]-'A']--;
}
for(int j = 0; right[j]; j++) {
temp[right[j]-'A']++;
}
}
}
int k = -1, ans = 0, flag = 0;
for(int i = 0; i < 12; i++) {
if(realCoin[i]) {
continue;
}
if(k < abs(temp[i])) {
k = abs(temp[i]);
ans = i;
flag = temp[i];
}
}
printf("%c is the counterfeit coin and it is %s.\n", ans+'A', flag>0?"heavy":"light");
}
return 0;
}