欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hdu 1004 Let the Balloon Rise

程序员文章站 2024-02-15 18:03:28
...

hdu 1004 Let the Balloon Rise

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

思路:
1.用一个字符数组储存颜色
2.用一个int 型数组储存某一种颜色的数量
3.输入一种颜色就开始与前面的颜色进行比对
4.如果与前面的颜色比对成功,则该颜色自加 1
5.遍历存储颜色数量的数组,找出最大值的下标,改下标即为该颜色的下标

代码实现及讲解:

#include<stdio.h>
#include <iostream>
#include <algorithm>
#include<string.h>
#include<math.h>
using namespace std;
int main()
{
    int N;
    while (scanf("%d",&N) != EOF && N)
    {
        char color[1001][15];	//定义字符数组储存颜色
        int i;
        int num[1001];	//定义int 型数组储存每种颜色的数量
        memset(num,0,sizeof(num));		//数组初始化
        int j;
        for (i=0;i<N;i++)	//输入颜色,注意,输入一次就查找一次
        {
            scanf("%s",color[i]);
            num[i] = 1;	//输入的该种颜色数量为 1
            for (j=0;j<i;j++)	//遍历先前输入的颜色
            {
                if (strcmp(color[j],color[i]) == 0)		//判断颜色是否相等
                     num[j] += 1,num[i] = 0;      //相等,改颜色自加,同时将num[i] = 0,因为前面找到该颜色,所以没必要重新开辟该颜色的下标
            }
        }
        int max = 0;		//查找最大下标
        for (i=1;i<j;i++)
            if (num[i] > num[max])
                max = i;
        printf("%s\n",color[max]);
    }
    return 0;
}