/*
题意:有十二枚硬币,其中一枚是假币,真币的重量相同,假币比真币轻或重。现给出三组称重的结果,求哪枚是假币,并判断比真币轻或重。
输入:左边的硬币,右边的硬币,右边硬币的结果(even/up/down) 左右两侧的硬币数量是一样的
输出:假币及其重量(heavy/light)
算法:模拟
难度:*
*/
#include <iostream>
#include <string>
using namespace std;
const int COUNT = 12;
int ans[COUNT];
// 返回两堆硬币称重的结果
string weight(string str1,string str2)
{
int len = str1.length();
int w1, w2;
w1 = w2 = 0;
for (int i=0; i<len; i++)
{
w1 += ans[str1[i]-'A'];
w2 += ans[str2[i]-'A'];
}
if (w1 == w2)
{
return "even";
}
else if (w1 > w2)
{
return "up";
}
else
{
return "down";
}
}
// 初始化数据ans
void init()
{
for (int i=0; i<COUNT; i++)
{
ans[i] = 0;
}
}
int main()
{
int n;
scanf("%d", &n);
string left[3],right[3],result[3];
while (n--)
{
init();
for (int i=0; i<3; i++)
{
cin >> left[i] >> right[i] >> result[i];
int len = left[i].length();
for (int j=0; j<len; j++)
{
ans[right[i][j]-'A'] = 1;
ans[left[i][j]-'A'] = 1;
}
}
int num;
string counterfeit ;
for (int i=0; i<COUNT; i++)
{
// 对每个被称过的硬币
if (ans[i] > 0)
{
// 假设第i个硬币是假币,而且是轻的
ans[i] -= 1;
int j;
for (j=0; j<3; j++)
{
if (weight(left[j],right[j]) != result[j])
{
break;
}
}
if (j >= 3)
{
counterfeit = "light";
num = i;
break;
}
// 假设第i个硬币是假币,而且是重的
ans[i]+=2;
for (j=0; j<3; j++)
{
if (weight(left[j],right[j]) != result[j])
{
break;
}
}
if (j >= 3)
{
counterfeit = "heavy";
num = i;
break;
}
ans[i] -= 1;
}
}
cout << char('A'+num) << " is the counterfeit coin and it is " << counterfeit << "." << endl;
}
}
poj1013 模拟
最新推荐文章于 2021-04-16 17:19:27 发布