二、stl ,模拟,贪心等 [Cloned] A - stl 的 map

本文介绍了一个简单的编程问题解决方法:统计比赛中每种颜色气球的数量并找出最流行的气球颜色。使用自定义结构体实现了一个简易的颜色计数系统。

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

原题:

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. 

题意:

输入一组数据包括各种颜色,找出出现次数最多的颜色

题解:这个题其实用map非常简单,就是做一个颜色对应个数的map就能解决问题,然而之前这个题我做过,当时还不会用stl所以用的结构体来做,稍微有点复杂,但是和map实际上意思差不多,从以前的文件里找了找直接复制过来了(懒死了我)

代码:AC

#include<iostream>
#include<cstring>
#include<cstdlib>

using namespace std;
typedef struct  ball
{
    char colour[20];
    int num;
}ball;

ball Ball[10000];

int insert(char str[],int n)
{
    int i, flag=1;
    int mid,low=0,high=n-1;
    if(n==0)
    {
        strcpy(Ball[0].colour,str);
        Ball[0].num=1;
        return 1;
    }
    while(low<=high)
    {
        mid=(low+high)/2;
        flag=strcmp(str,Ball[mid].colour);
        if(flag==0)
            break;
        else if(flag<0)
        {
            high=mid-1;
        }
        else
            low=mid+1;
    }
    if(flag==0)
    {
        Ball[mid].num++;
    }
        else
        {
            for(i=n;i>low;i--)
                Ball[i]=Ball[i-1];
            strcpy(Ball[low].colour,str);
            Ball[low].num=1;
            n++;
        }
        return n;
}
int GetMax(int n)
{
    int i,max=0;
    for(i=0;i<n;i++)
    {
        if(Ball[i].num>Ball[max].num)
            max=i;
    }
    return max;
}
int main()
{
    char str[20];
    int i,len,n,pos;
    cin>>n;
    while(n)
    {
        len=0;
        for(i=0;i<n;i++)
        {
            cin>>str;
            len=insert(str,len);
        }
        pos=GetMax(len);
        cout<<Ball[pos].colour<<endl;
        cin>>n;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值