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.
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
题目意思就是输入n,代表有多少个气球,然后输入气球颜色,统计出现次数最多的那种颜色。
因为用数组存气球颜色的话要运用到字符串匹配,每插入一种颜色还要判断是否是已有的颜色。
所以用 map数据结构比较方便,就要注意如何去判断map已有,和获取值再加一。
我这一块很容易忘,要找个时间好好总结一波。
注意的点如下:
1:用字符串保存输入的颜色(因为我的map<string,int>)
2: map<string,int>::iterator zz;
zz = qiqiu.find(yanse);//如果找不到,zz==qiqiu.end(),用这点判断是否是已经出现的颜色
qiqiu[yanse]=1; //这样就可以直接插入颜色,并赋值,比较容易记和理解
就像运用数组一样,如果存在就直接 qiqiu[yanse]++就好了
在添加修改过程中不断与最大标记做比较,并记录临时最大答案,最后全部输入完成直接输出答案就好了。
下面附上代码:
#include <iostream>
#include <queue>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
int main()
{
map<string,int> qiqiu;
map<string,int>::iterator zz;
int cas,ma;
string yanse;
string ans="no";
while(cin>>cas)
{
if(cas==0)
break;
ma=0;
qiqiu.clear();
while(cas--)
{
cin>>yanse;
zz = qiqiu.find(yanse);
if(zz==qiqiu.end())//找不到,则插入
{
qiqiu[yanse]=1;
}
else
{
qiqiu[yanse]++;
}
if(qiqiu[yanse]>ma)
{
ma=qiqiu[yanse];
ans=yanse;
}
}
cout<<ans<<endl;
}
return 0;
}