Let the Balloon Rise

来源:互联网 发布:java trim 全角空格 编辑:程序博客网 时间:2024/03/29 08:01

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


Let the Balloon Rise

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

中文翻译大致意思是:


    输入包含多个测试案例。每一个测试例以数字N开头(0 <N <= 1000) - 分布气球的总数。 接下来的N行是每一种颜色。 气球的颜色用一个字符串表示,且该字符串最多用15个小写字母表示。 当输入N = 0时试验终止输入,且此测试不被处理。
    输出对每一种情况下彩色气球数最多的那个气球的名字。并且保证每个测试用例,都有一个独特的解决方案。
 
    一开始看到这道题的时候我就在想该用什么方法存放这些气球颜色,可以用STL模版,也可以用结构体数组。
    我这里用结构体做,先定义一个结构体,结构体名字叫Balloon,在结构体中定义一个字符串变量s,然后再定义一个Balloon类型的数组c[1001],用于存放数据。主函数中,先把测试例按题意格式输入,然后用一个for语句计算每个颜色的数量,最后在用一个for语句计算输出颜色数量最多那个颜色名称。
 
代码:

#include<iostream>using namespace std;struct Balloon{ string s;};Balloon c[1001];int sum[1001];int main(){    int n;    while(cin>>n && n)    {    memset(sum,0,sizeof(sum));        int i,j;        for(i=0; i<n; i++)           cin>>c[i].s;for(i=0; i<n; i++)        {            for(j=0; j<n; j++)            {                if(c[i].s==c[j].s)                    sum[i]++;            }        }        int k=0,r=0;        for(i=0; i<n; i++){            if(sum[i]>k)            {   k=sum[i];                r=i;            }        }        cout<<c[r].s<<endl;    }    return 0;}