ACM程序设计 书中题目O(map统计字符串出现的次数)

来源:互联网 发布:js中的for循环 编辑:程序博客网 时间:2024/05/22 11:35

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

这道题的意思是输入很多字符串找到出现次数最多的字符串

对于这道题,我第一时间想到的是用string数组,但实现起来很困难而且复杂度很高,以至于我提交多次失败。

如果用map的对应关系来做就很容易,但我map不熟,现学了许多关于map的知识,大致内容在前面两篇博客。

#include<bits/stdc++.h>using namespace std;int main(){        int a,i,n,max;        string m;        map<string,int>pl;        map<string,int>::iterator p1,p2;        while(cin>>n)        {                if(n==0)                        break;                for(i=0;i<n;i++)                {                        cin>>m;                        pl[m]++;                }                max=0;                for(p1=pl.begin();p1!=pl.end();p1++)                        if(max<p1->second)                        {                                max=p1->second;                                p2=p1;                        }                cout<<p2->first<<endl;                pl.clear();        }}



0 0
原创粉丝点击