最近做题有点浮躁~于是从HDU第一题开始刷,刷到1004题的时候突发奇想来复习一发很久没有用到过的map
题意是给你n个气球,每个气球有一种颜色,让你求出数量最多的气球颜色
因为颜色是气球数量的识别关系,所以把颜色设置为key,数量设置为value,这样来根据颜色来增加查找数量
向map容器中插入元素的方法有很多种
比如map的insert函数,把key和value填充至一个pair<,>,然后insert(pair<,>)
还有本处用到的类数组用法,注意下标内填入的是key
第一种是用迭代器遍历map内部去找最大值
要注意迭代器前要有对应的容器模板
第二种是对内部元素从大到小排序,直接输出排序后第一个元素的value
要注意的是map是红黑树结构,因此要对value排序时,不能直接用sort函数去排,要先用STL容器的克隆构造转换为线性的vector等容器去排
容器内要用和map结构相同的pair<key,value>元素,并写出对应的比较函数
话不多说,直接看代码吧
Let the Balloon Rise
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 145040 Accepted Submission(s): 57518
Problem Description
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges' favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.
This year, they decide to leave this lovely job to you.
This year, they decide to leave this lovely job to you.
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) -- the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.
A test case with N = 0 terminates the input and this test case is not to be processed.
A test case with N = 0 terminates the input and this test case is not to be processed.
Output
For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.
Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0
Sample Output
red
pink
#include <iostream> #include <map> #include <vector> #include <string> #include <algorithm> using namespace std; bool cmp(const pair<string,int>& a,const pair<string, int>& b) { return a.second > b.second; } struct CMP { bool operator() (const pair<string, int>& a, const pair<string, int>& b) const { return a.second > b.second; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; while (cin>>n && n) { map<string, int> mp; string str; for (int i = 0; i < n; i++) { cin >> str; int flag = mp.count(str); if (!flag) mp[str] = 1; else mp[str]++; } //1 int max = 0; for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++) { if (it->second > max) { max = it->second; str = it->first; } } cout << str << endl; //2 vector<pair<string, int> > v(mp.begin(),mp.end()); sort(v.begin(), v.end(), cmp); cout << v.begin()->first << endl; } return 0; }