题目:
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
题意:先输入一个整数(1-1000),表示输入的表示颜色的字符串的个数,输出重复次数最多的颜色。
复习一下strcmp函数的用法设这两个字符串为str1,str2,
若str1==str2,则返回零;
若str1< str2,则返回负数;
若str1>str2,则返回正数。
AC的c语言代码:
#include<stdio.h>
#include<string.h>
char str[1005][15];
int main(){
int n;
while(scanf("%d", &n) && n!= 0){
for(int i = 0; i < n; i++)
scanf("%s", str[i]); //注意字符数组的输入
int count[1005];
int max = 0, flag = 0;
memset(count, 0, sizeof(count)); //将count里的值全部初始化成0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(strcmp(str[j], str[i]) == 0)
count[i]++;
}
}
for(int i = 0; i < n; i++)
if(count[i] > max){
max = count[i];
flag = i;
}
printf("%s\n",str[flag]);
}
return 0;
}
用map的AC代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
int main(){
int n;
string color, temp;
while(scanf("%d", &n) &&n){
map<string, int>balloon;
for(int i = 0; i < n; i++){
cin>>color;
balloon[color]++;
}
//可以吧map里面的key理解为数组下标,value为数组的值
int max = 0;
map<string, int>::iterator it;
for(it = balloon.begin(); it != balloon.end(); it++){
if((*it).second > max){
max = (*it).second;
temp = (*it).first;
}
}
cout<<temp<<endl;
}
return 0;
}