问题:
http://acm.hdu.edu.cn/showproblem.php?pid=1004
题解:
水题,解题的关键在于如何记录下出现的气球的颜色及其出现的次数(数据结构的选取),显然,这里可以使用Map。
具体思路见代码:
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
int main()
{
int n;
map<string, int> cnt_colors; // 定义一个从string到int的map
while (scanf("%d", &n) && n) {
cnt_colors.clear(); // 使用前先清空map
for (int i = 0; i < n; ++i) {
string *tmp = new string();
cin >> *tmp;
if (cnt_colors.find(*tmp) == cnt_colors.end())
cnt_colors[*tmp] = 1; // 第一次出现该颜色初始为1
else
++(cnt_colors[*tmp]); // 否则,+1
}
string mostPopularColor;
for (map<string, int>::iterator it = cnt_colors.begin(); it != cnt_colors.end(); ++it) {
if (it == cnt_colors.begin()) {
mostPopularColor = it->first;
continue;
}
if (cnt_colors[it->first] > cnt_colors[mostPopularColor])
mostPopularColor = it->first;
}
cout << mostPopularColor << endl;
}
return 0;
}