题意
题目的大概意思是,有A到L号硬币,其中有一个的重量与其他的不同,现通过三次比较来找出哪个硬币是重量不同的,以及它是较轻还是较重。
分析
因为一定有解,所以先假定每个硬币的权值为0,先统计所有硬币的Even, Up,Down状态。从Up状态中找到没有在Even时出现过的硬币,让剩下的每一个硬币的权值减1,然后从Down状态中找到没有在Even时出现过的硬币,让剩下下的每一个硬币的权值加1,最后权值绝对值最大的那个便是不同的硬币,权值为负则较轻,反之较重。
代码如下:
Memory: 212K Time: 0MS Length:53LINES
#include<iostream>
#include<string>
#include<map>
using namespace std;
void Distinct(const string & Even, const string& Up, const string& Down, map<char, int>& Suspect)
{
for (string::size_type i = 0; i < Up.length(); ++i)
if (Even.find(Up[i]) == string::npos) Suspect[Up[i]]--;
for (string::size_type i = 0; i < Down.length(); ++i)
if (Even.find(Down[i]) == string::npos) Suspect[Down[i]]++;
};
int main()
{
int Count = 0;
cin >> Count;
while (Count--)
{
string Even;
string Up;
string Down;
map<char, int> Suspect;
for (int i = 0; i < 3; ++i)
{
string First, Second, Third;
cin >> First >> Second >> Third;
if (Third == "even") Even = Even + First + Second;
else if (Third == "up")
{
Up += Second;
Down += First;
}
else
{
Up += First;
Down += Second;
}
}
Distinct(Even, Up, Down, Suspect);
char Key = Suspect.begin()->first;
int Value = Suspect.begin()->second;
for (map<char, int>::iterator iter = Suspect.begin(); iter != Suspect.end(); ++iter)
{
if (abs(iter->second) > abs(Value))
{
Key = iter->first;
Value = iter->second;
}
}
if (Value > 0) cout << Key << " is the counterfeit coin and it is heavy." << endl;
else cout << Key << " is the counterfeit coin and it is light." << endl;
}
return 0;
}