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.
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.
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
题目大意就是输入一列颜色,找出出现次数最多的那个颜色;
思路如下:
1.利用map存储气球颜色和数量;
2.利用迭代器找出数量最多的颜色;
3.输出颜色。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<string,int>color; //map数组存颜色和数量
map<string,int>::iterator p,q; //迭代器p用于查找,q用于储存
int n,i,max;
string x;
while(cin>>n)
{
if(n==0)
break;
else
{
max=0; //max用于储存最多气球的数量,用于比较,每次使用前归零
for(i=0;i<n;i++)
{
cin>>x;
color[x]++;
}
for(p=color.begin();p!=color.end();p++)
{
if(max<p->second)
{
max=p->second; //查找并储存颜色
q=p;
}
}
cout<<q->first<<endl;
color.clear(); //清空容器
}
}
}
题目也可以用多个数组来做,但是那样会比较麻烦而求有超时的风险,map是不错的解决办法