This is an intellectual question.
Ideas:
1. If it is a counterfeit currency, the balance will be unbalanced every time.
2. If the balance is horizontal, all of them must be real coins.
With this feature, we can use hash tables to write simple programs.
If enumeration is used, then (easy ?) Hundreds of lines of code.
Of course, the question provides the condition that the only counterfeit currency can be found.
If this condition is not met, the result may not be identified by three calls.
# Include
# Include
# Include
Using namespace std; class CounterfeitDollar {const static int ALPHA = 12; const static int TIMES = 3; string s1, s2, s3; public: CounterfeitDollar () {int n; cin> n; while (n --) {int tbl [ALPHA] [TIMES] = {0}; int balance [TIMES] = {0 }; for (int I = 0; I <TIMES; I ++) {cin> s1> s2> s3; for (int j = 0; j <(int) s1.size (); j ++) {tbl [s1 [j]-'a'] [I] =-1; tbl [s2 [j]-'a'] [I] = 1;} if ('E' = s3 [0]) balance [I] = 0; else if ('D' = s3 [0]) balance [I] = 1; else balance [I] =-1 ;}for (int I = 0; I <ALPHA; I ++) {if (balance [0] =-tbl [I] [0] & balance [1] =-tbl [I] [1] & balance [2] = =-tbl [I] [2]) {cout <
Update a new solution:
1 if it is even, then all are real coins, so set it to 10
2 If the coin is on the light side, then -- if the coin is on the heavy side, then ++
3. Finally, find the coin with the greatest difference.
4. If the counterfeit currency is negative, it is lighter than the real currency. If it is positive, it is heavier than the real currency.
This is an original program, and it is easier to understand than the previous one.
#include
#include
#include
using namespace std;class CounterfeitDollar_2{const static int ALPHA = 12;const static int TIMES = 3;string s1, s2, s3;public:CounterfeitDollar_2(){int n;cin>>n;while (n--){int tbl[ALPHA] = {0};int balance[TIMES] = {0};for (int i = 0; i < TIMES; i++){cin>>s1>>s2>>s3;if ('e' == s3[0]){for (int i = 0; i < (int)s1.size(); i++){tbl[s1[i] - 'A'] = 10;tbl[s2[i] - 'A'] = 10;}}else if ('d' == s3[0]){for (int i = 0; i < (int)s1.size(); i++){if (tbl[s1[i] - 'A'] != 10) tbl[s1[i] - 'A']--;if (tbl[s2[i] - 'A'] != 10) tbl[s2[i] - 'A']++;}}else{for (int i = 0; i < (int)s1.size(); i++){if (tbl[s1[i] - 'A'] != 10) tbl[s1[i] - 'A']++;if (tbl[s2[i] - 'A'] != 10) tbl[s2[i] - 'A']--;}}}int id = 0, diff = 0;for (int i = 0; i < ALPHA; i++){if (tbl[i] != 10 && diff < abs(tbl[i])){diff = abs(tbl[i]);id = i;}}cout<