HUD 1004

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

数组版本没什么好说的,用color[1000] [16] 记录下各种颜色,num[1000] 记录下颜色的出现次数,两个循环,记录下最大的数,再从color里面找出对应的颜色。

数组版本

#include<cstdio> 
#include<iostream>
#include<cstring>

using namespace std;

char color[1000][16];
int num[1000];

int main()
{
    memset(num,0,sizeof(num));
    int n,t=0;
    num[1]=1;
    while(cin>>n,n)
    {
        for(int i=1;i<=n;i++)
            scanf("%s",color[i]);
        for(int i=2;i<=n;i++)
            for(int j=1;j<i;j++)
                if(strcmp(color[i],color[j])==0)
                    num[i]++;
        int max=0;
        for(int i=1;i<=n;i++)
            if(max<num[i])
            {
                max=num[i];
                t=i;
            }
        cout<<color[t]<<endl;
    }
    return 0;   
}

一看到题目想到建立一个映射关系,算出每种颜色出现次数,找到最大出现次数对应的颜色即可。想用map来实现,因为对map不是很熟悉,结果迭代器那边不会实现,查找相关资料后,试着写了下,map简直好用到不行!

map版本

#include<iostream> 
#include<string>
#include<map>

using namespace std;

int main()
{
    map<string,int> balloon;
    string color,po_color;
    int n;
    while(cin>>n,n) 
    {
        balloon.clear();
        for(int i=0;i<n;i++)
        {
            cin>>color;
            balloon[color]++;
        }
        int max=0;

        map<string,int>::iterator it;
        for(it=balloon.begin();it!=balloon.end();it++)
        {
            if(max<it->second)
            {
                max=it->second;
                po_color=it->first;
            }
        }
        cout<<po_color<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hjq_xidian/article/details/52641036
HUD