HDOJ_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


对于这道题目,我一开始的思想是建一个表,将键值,颜色一一对应放在表中,同时建立一个和键值同步的数组,用于记录颜色的重复次数。利用map的find方法按颜色查找表中是否已经存在该颜色,这样可以减少遍历的次数,减少负责度,但是发现map的find方法是需要按照键值还查找的,因此错误。

最终还是乖乖的二重遍历,在存放颜色数组时有两种方式:

1.char类型的二维数组,可以用strcmp函数比较字符串是否一致。

    strcmp(str1,str2),若str1==str2,则返回零;若str1>str2,则返回正数;若str1<str2,则返回负数。

2.string类型的一维数组,可以用compare函数比较字符串是否一致。

    compare(string s1,string s2)==0时,s1与s2一致。

代码如下:

#include <iostream>
#include <string.h>
#include <string>
#include <map>
#include<vector>
using namespace std;

int main(){
    int n;
    int i = 0;


    while(cin>>n&&n!=0){
//      cout<<n<<endl;
        int p = 0;//记录最多气球的键值 
        vector<int> cnum;//用于记录颜色数量 
        vector<string> color;//用于记录颜色 
        for(i = 0;i<n;i++){
            string s;
            cin>>s;
            color.push_back(s);
            cnum.push_back(0); 
        }
        int max = -1;
        for(i = 0;i<n;i++){
            for(int j = i+1;j<n;j++){
                if(color[i].compare(color[j])==0){
                    cnum[i]++;
                }
            }
            if(cnum[i]>max){
                max = cnum[i];
            }
        }

        for(int j = 0;j<n;j++){
            if(max==cnum[j]){
                cout<<color[j];
            }
        }
        if(n)
        cout<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值