HDU 1004

本文探讨了一种计算颜色出现次数的算法,并通过对比两种实现方式,展示了如何利用map数据结构优化代码,提高效率。原始方法使用了结构体和双重循环进行颜色匹配计数,而优化后的代码采用map来存储颜色及其对应的计数,简化了流程,提高了查找速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题初看觉得很简单,但是综合很多特性,虽然用的方法比较笨,但是成功做出来了。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <set>
#include <sstream>
#include <vector>
using namespace std;

struct Color{
    int count = 0;
    string color;
};
Color colors[1000] = {};

int main(){
    int n;
    while(cin>>n && n!= 0){

        for(int i=0;i<n;i++){
            cin>>colors[i].color;
            colors[i].count= 0;
        }
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(strcmp(colors[i].color.data(),colors[j].color.data()) == 0){
                    colors[i].count++;
                }
            }
        }
        int max = colors[0].count;
        int tmp = 0;
        for(int i=0;i<n;i++) {
            if (colors[i].count > max) {
                max =colors[i].count;
                tmp = i;
            }
        }
        cout<<colors[tmp].color<<endl;
    }

    return 0;
}

写出来之后参考大佬的AC方式,比我写的优雅多了。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <set>
#include <sstream>
#include <vector>
#include<map>

using namespace std;
map<string,int> colors;

int main(){
    int n;
    while(cin>>n && n!= 0){

        colors.clear();
        int max = 0;
        string key,p;
        for(int i=0;i<n;i++){
            cin>>key;
            colors[key]++;
            if(colors[key] > max){
                max = colors[key];
                p = key;
            }
        }
        cout<< p <<endl;

    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值