杭电ACM—1004 Let the Balloon Rise

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1004


题目:

   Problem Description
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


这个题目要求我们输入n个单词并找出其中重复次数最多的单词输出。这个题目需要用到容器,我就使用了vector,先把输入的

单词放到容器中储存,然后用sort函数进行排序,排序完之后相同的单词就会排在一起,然后我们便可以找到重复次数最多的

单词,但一定要谨记在最后一个单词进行比较完之后,单词的重复个数必须与之前单词重复个数进行比较。这个题目也可以用

map容器来做,因为map容器的下标不予许重复,根据此特性我们可以更方便的求出结果。


代码如下:

<   1  >   vector容器:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n,i,j;
	string str;
   	vector<string> vec;
	while(cin>>n && n!=0)
	{
		int b=0,a=1;
		vec.clear();
		for(i=0;i<n;i++)
		{
			cin>>str;
			vec.push_back(str);
		}
		sort(vec.begin(),vec.end());
		for(i=1;i<n;i++)
		{
			if(vec[i]==vec[i-1]) a++;
			else 
			{
				if(a>b) {b=a;str=vec[i-1];}
				a=1;//一旦vec[i]!=vec[i-1],a必须重新从1开始
			}
		}
		if(a>b) cout<<vec[n-1]<<endl;//最后单词重复个数与b相比
		else cout<<str<<endl;
	}
	
	return 0;
}


<  2  >  map容器
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
    int n,i,max=0;
    string str;
       map<string ,int> vec;
    map<string,int>::iterator it;
    while(cin>>n  && n!=0)
    {
        vec.clear();
        for(i=0;i<n;i++)
        {
            cin>>str;
            vec[str]++;
        }
        for(it=vec.begin();it!=vec.end();it++)
        {
            if(it->second>max)
            {
                max=it->second;//求个数最多的
                str=it->first;//个数最多的字符所对应的下标
            }
        }
        cout<<str<<endl;
    }
    return 0;
}



 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值