杭电oj HDOJ 1004 Let the Balloon Rise
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.
题目大意
每次根据系统给的N个测试数据,输出其中出现次数最多的那个测试数据。
解题思路
- 构造一个“balloon”结构体,结构体有气球颜色和出现次数
- 定义一个balloon结构体数组来存储接收到的气球颜色和其出现的次数。
- 接收结束后找出数组中出现次数最多的气球颜色,并输出。
- 清除之前接收到的数据,供下一轮接收数据使用。
本人的C++解决方案
#include <iostream>
#include <string>
using namespace std;
struct ballon
{
string color;
int num;
};
int main()
{
int N, i, j, max, count;
string str;
struct ballon b[1000];
while (cin>>N) {
if (N == 0) {
break;
}
if (N <= 0 || N > 1000) {
continue;
}
count = 0;
for (i = 0; i < N; i++) {
cin>>str;
// 第一个测试数据直接插入数组中
if (i == 0) {
b[0].color = str;
b[0].num = 1;
count++;
}
// 检查该颜色是否是之前出现过的颜色
for (j = 0; j < i; j++) {
if (str == b[j].color) {
b[j].num++;
break;
}
}
// 把第一次出现的气球颜色插入数组中
if (j == i && i != 0) {
b[j].color = str;
b[j].num = 1;
count++;
}
}
// 找出出现次数最多的气球颜色
max = 0;
for (i = 0; i < count; i++) {
if (b[i].num > b[max].num) {
max = i;
}
}
cout<<b[max].color<<endl;
// 清除存储数据,供下一轮测试用例使用
for (i = 0; i < count; i++) {
b[i].color = "";
b[i].num = 0;
}
}
return 0;
}
代码通过HDOJ平台运行检查,如发现错误,欢迎指出和纠正,谢谢!