map容器

来源:互联网 发布:安装ubuntu时怎么分区 编辑:程序博客网 时间:2024/05/17 06:58

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1004

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
5greenredblueredred3pinkorangepink0
Sample Output
redpink

解法一:模拟

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;struct J//结构体的定义{    int a;    char b[20];} s[1005];int cmp(J x,J y)//自定义cmp函数,用来排序{    return x.a>y.a;}int main(){    int t;    while(~scanf("%d",&t)&&t)    {        int k=0;        for(int i=0;i<1005;i++)            s[i].a=0;        for(int i=0; i<t; i++)//两层for循环很关键        {            scanf("%s",s[k].b);            for(int j=0; j<k; j++)            {                if(!strcmp(s[k].b,s[j].b))                {                    s[j].a++;                    break;                }            }            s[k++].a++;        }        sort(s,s+t,cmp);        printf("%s\n",s[0].b);    }}解法二:map容器:
#include <iostream>#include <string>#include <iterator>#include <map>#include<stdio.h>using namespace std;map<string,int>mapp;char s[30];int main(){    int t;    while(~scanf("%d",&t)&&t)    {        mapp.clear();        int sum=0;       string sum1;        for(int i=0;i<t;i++)        {            scanf("%s",s);            mapp[s]++;        }        for(map<string,int>::iterator iter=mapp.begin();iter!=mapp.end();iter++)        {            if(iter->second>sum)            {                sum1=iter->first;                sum=iter->second;            }        }        cout<<sum1<<endl;    }}

原创粉丝点击