Let the Balloon Rise
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 134935 Accepted Submission(s): 53303
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.
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.
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
使用字符串解题思路:
将字符串储存在字符串数组中,遍历查询以前输入的所有字符串,并且对每一个字符串所对应的数组进行计数,定义一个数, 找出出现次数最多的字符串的下标,输出
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[1005];char b[10005][30];//a是计数数组,如果使用标记数组,尽量不要用int
int main()
{
int m;
while(cin >> m && m!= 0)
{
memset(a,0,1005);
cin >> b[0];
for(int i = 1;i < m;i++ )
cin >> b[i];
for(int i = 1;i < m;i++)
{
for(int j = 0;j < i -1;j++)
{
if((strcmp(b[i],b[j]) == 0))
a[i]+=1;
}
}
int mx = a[0],t = 0;
for(int i = 1;i < m;i++)
{
if(mx < a[i])
{
mx = a[i];//这里一定要更新mx的值
t = i;
}
}
cout << b[t] << endl;
}
使用STL解题思路(map容器):
(先介绍下map,毕竟楼主也刚学c++)map映照容器的元素是由一个键值和一个映照数据组成的,键值和映照数据之间有 一一映照的关系。map映照容器的数据结构也是采用红黑树来实现的,插入元素的键值不允许重复,比较函数只对元素的键值进行比较,元素的各项数据可以通过键值检索出来。
AC代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
int m;
map<string,int>ma;//定义map容器
while(cin >> m && m != 0)
{
string a;
for(int i = 0;i < m;i++)
{
cin >> a;
ma[a]++;//映照数据计数
}
map<string,int>::iterator it;//定义前向迭代器
int manx = -230;string mx;
for(it = ma.begin();it != ma.end();it++)//遍历开始到结束
{
if((*it).second > manx)
{
manx = (*it).second;//一定更新manx的值
mx = (*it).first;
}
}
cout << mx <<endl;
ma.clear();//清空map容器ma
}
return 0;
}