Description
n个色盲聚在一起,讨论一块布的颜色。尽管都是色盲,却盲得各不相同。每个人都有自己的主张,争论不休。最终,他们决定采取民主投票的方式决定布的颜色,不管布同不同意。某种颜色用字符串表示(字符串为颜色单词或词组,也就是可能有被空格隔开的两个单词组成的颜色词组),只要字符串不同,程序即判断颜色不同。现在给出这n个人所选择的颜色,输出最有可能的颜色(也就是获得投票最多的颜色),如果有多个颜色获得了最多的投票,则将它们按字典序分行全部输出。
Input
第一行一个正整数n,表示色盲的人数
接下来n行,每行一句话
Output
若干行,获得投票最多的颜色,按字典序输出
Sample Input 1
5 red blue black black blue
Sample Output 1
black blue
解题思路:这里使用c++中STL里的关联容器 map;用来记录一个颜色出现的次数,其数据结构为map<string,int>,颜色每出现一次,则其对应的value值加1,最后通过两次遍历得到答案,第一次遍历找到出现次数最多的颜色,第二次遍历寻找与第一次遍历找到的颜色的出现次数相同的所有颜色,最后输出答案。
源代码:
#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include<map>
using namespace std;
class QuickSort
{
private:
map<string, int> ma;
int n;
public:
QuickSort() {
string str;
cin >> n;
for (int i = 0; i < n; i++) {
getline(cin,str); //这里要注意不能使用cin,因为cin不能读取空格,会导致无法读取到词组
ma[str]++;
}
int index = ma[str];
priority_queue<string, vector<string>, greater<string> >T;
for (map<string, int>::iterator it = ma.begin();it != ma.end();it++) {
if (it->second > index) {
index = it->second;
}
}
for (map<string, int>::iterator it = ma.begin();it != ma.end();it++) {
if (it->second == index) {
index = it->second;
T.push(it->first);
}
}
while (!T.empty()) {
if (T.size() == 1) {
cout << T.top();
}
else {
cout << T.top() << endl;
}
T.pop();
}
}
};
int main()
{
QuickSort *Q = new QuickSort();
return 0;
}