一道模拟砝码称重的题目,但是这题是判断硬币的。
题目针对每一组的测试样例会给出三组测量的结果。并且保证肯定会确定有一枚或轻或重的假币藏在这几个硬币中。
如果按照一般的思路来做,会发现逻辑还是比较复杂和难以判断的。
但是有一种比较巧妙的思路,找出题中的规律并进行计数,就能得到最后的答案。
代码如下
#include<iostream>
#include<string>
using namespace std;
#inlcude<iostream>
#include<string>
using namespace std;
using namespace std;
int main()
{
int n;
cin >> n;
while (n--)
{
int letter[12] = { 0 };
int bad = 0;//记录有几次天平不平衡
for (int i = 0; i < 3; i++)
{
string a, b, c;
cin >> a >> b >> c;
if (c == "up")
{
for (int j = 0; j < a.size(); j++)
letter[a[j] - 65] ++;//左边重的都+1
for (int j = 0; j < b.size(); j++)
letter[b[j] - 65] --;//右边轻的都-1
bad++;//不平衡次数+1
}
if (c == "down")
{
for (int j = 0; j < a.size(); j++)
letter[a[j] - 65] --;
for (int j = 0; j < b.size(); j++)
letter[b[j] - 65] ++;
bad++;
}
if (c == "even")
for (int j = 0; j < a.size(); j++)
letter[a[j] - 65] = letter[b[j] - 65] = 9;
//不一定非要是9 其实只要是一个比3大的数就行 因为最多有3次不平衡
}
for (int i = 0; i < 12; i++)
{
if (letter[i] == bad) //如果有一个有bad次++
cout << char(i + 65) << " is the counterfeit coin and it is heavy." << endl;
if (letter[i] == -bad)//如果有一个有bad次--
cout << char(i + 65) << " is the counterfeit coin and it is light." << endl;
}
}
return 0;
}