Let the balloon rise-by map

题目链接(https://vjudge.net/contest/235899#problem/A)

题目如下

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

这道题提示用map做,学了学STL中的map

代码如下

#include<cstdio>
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
	int n;
	map<string,int>color;
	while(scanf("%d",&n)==1&&n)
	{
		color.clear();
		int maxn=-1;
		for(int i=0;i<n;i++)
		{
			string str;
			cin>>str;
			color[str]++;
			if(color[str]>maxn)maxn=color[str];
		}
		map<string,int>::iterator it;
		for(it=color.begin();it!=color.end();it++)
		{
			if(it->second==maxn)cout<<it->first<<"\n";
		}
	}
	return 0;
}

第18行color[str]的初值默认为零,虽然没找到相关的解释,但是我经过试验,map[str]的初值的确是零,如有错误,请联系更正

第21行map<string,int>::iterator it是迭代器,理解为指针

第24行it->first意思是it指向map的键(key)即map<string,int>中的string,同理it->secong意思是it指向map的值(value)

猜你喜欢

转载自blog.csdn.net/qq_41626975/article/details/81411962