HDU 让气球上升 1004 (map的用法)

HDU 让气球上升 1004 (map的用法)

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

个人分析:

这个题作为STL入门是比较经典的,主要是掌握map的用法以及迭代器的使用。那么分析一下题目吧:这个题意思就是找出众数 大概意思应该懂了哦! 也就是气球颜色最多的那个 我们可以建map<string,int>类型的 然后每遇到相同的map[string]++ 其实直接看源代码应该能直接看懂的(前提是map基本语法要明白!)后面一个重要的迭代:

int maxn=0;
        for(it=m.begin();it!=m.end();it++)
        {
            if(it->second>maxn)
            {
                maxn=it->second;
                s=it->first;
            }
        }
        cout<<s<<endl;

这里就是找到出现最多的那个数 相当于找出最大数 先申明一个manx 作比较 如果比它大 那么就交换 一直遍历结束停止 然后就输出string->first 就AC了 注意我们用了string类型的要申明头文件#include 我已经好几次没写这个头文件了!!!

具体代码如下:
AC

#include<iostream>
#include<map>
#include<string>
using namespace std;
string str[1008];
map<string,int> m;
string s;
int main() {
    int n;
    map<string,int>::iterator it;
    while(cin>>n&&n)
    {
        m.clear();
        for(int i=0;i<n;i++)
        {
            cin>>str[i];
            m[str[i]]++;
        }
        int maxn=0;
        for(it=m.begin();it!=m.end();it++)
        {
            if(it->second>maxn)
            {
                maxn=it->second;
                s=it->first;
            }
        }
        cout<<s<<endl;
    }
	return 0;
}

学如逆水行舟,不进则退

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/87358333