题目链接点击打开链接
Let the Balloon Rise
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 94240 Accepted Submission(s): 35979
This year, they decide to leave this lovely job to you.
A test case with N = 0 terminates the input and this test case is not to be processed.
5 green red blue red red 3 pink orange pink 0
red pink
先用一种很low的办法,开一个二维字符数组ccolor,用来记录出现过的字符串,因为n的规模为1000, 所以第一维规模为1000 + 10, 第二维大于字符串长度为20,同时开一个记录出现次数的数组a[1000 + 10],并全部初始化为0,同时设置变量count表示出现过的不重复的字符串的数量。
每读入一个字符串,将ccolor第一维从0到count进行循环,如果发现匹配的字符串ccolor[j],则,a[j]++;如果没有找到,则count++。
最后将数组a从0到count进行遍历找出值最大的下标i,输出才color[i]即可。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
char color[20];
char ccolor[1000 + 10][20];
int a[1000 + 10];
int main()
{
int n;
while(scanf("%d", &n) != EOF){
if(n == 0)
break;
memset(a, 0, sizeof(a));
int count = 0;
for(int i = 0; i < n; i++){
scanf("%s", color);
int flag = 0;
for(int j = 0; j < count; j++){
if(strcmp(ccolor[j], color) == 0){
flag = 1;
a[j]++;
break;
}
}
if(flag == 0)
strcpy(ccolor[count++], color);
}
int ans = 0, num;
for(int i = 0; i < count; i++){
if(a[i] > ans){
ans = a[i];
num = i;
}
}
printf("%s\n", ccolor[num]);
}
return 0;
}
另一种很简便的方法就是用map容器,只能说map功能好强大,顺便也学习下map的用法,基本的操作函数有:
map是一种关联式容器,包含“关键字/值”对
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp()返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数
用了两种做法写的,一种是用迭代器的,另一种是不用迭代器的,附上代码
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
int main()
{
int n;
map<string, int> ballon;
string maxcolor;
char color[20];
while(scanf("%d", &n) != EOF){
if(n == 0)
break;
ballon.clear();
for(int i = 0; i < n; i++){
scanf("%s", color);
ballon[color]++;
}
map<string, int>::iterator it;
int maxn = 0;
for(it = ballon.begin(); it != ballon.end(); it++){
if(it->second > maxn){
maxn = it->second;
maxcolor = it->first;
}
}
/*
int max = 0;
for(int i = 0; i < n; i++){
scanf("%s", &color);
ballon[color]++;
if(ballon[color] > max)
maxcolor = color;
}*/
printf("%s\n", maxcolor.c_str());
}
return 0;
}