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

原题:

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;
}

猜你喜欢

转载自blog.csdn.net/npuyan/article/details/81368945
今日推荐