HDOJ 1004 - Let the Balloon Rise(让气球飞起来)

Let the Balloon Rise

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 138223    Accepted Submission(s): 54591

 

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
 
分析

这题蕴藏了一个常识:在ACM比赛中一个队伍每解决一个问题,就可以拿到一个气球,每道题对应的气球颜色不同。不过即使不了解这个常识也不影响做这道题。
注意数据范围:0<N<=1000,颜色字符串为最多15个字符的字符串。
并且注意输出描述中已经保证每组输入只会有唯一一个输出。
因此只要建立两个长度为N的一维数组即可保存所有可能的颜色及其出现次数,只要一个变量即可保存该颜色对应的下标(或者用两个变量,即颜色和出现次数,保存出现次数最多的颜色相关信息)。
这题节省时间最关键的地方在于如何查找颜色是否已经出现过,即是否已在数组中。线性查找较慢,使用二分查找可以很大地提高速度。

 
代码
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int search(string color[1000], int len, string str, int begin, int end);
 6 
 7 int main()
 8 {
 9     int n;
10 
11     while (cin >> n && n != 0) {
12         string color[1000];
13         string str, maxStr;
14         int colorCount[1000];
15         int len = 0, maxCount = 0;
16 
17         for (int i = 0; i < n; i++) {
18             cin >> str;
19             int index = search(color, len, str, 0, 0);
20             if (index == -1) {
21                 color[len] = str;
22                 colorCount[len] = 1;
23                 index = len;
24                 len = len + 1;
25             } else {
26                 colorCount[index]++;
27             }
28             if (colorCount[index] > maxCount) {
29                 maxStr = str;
30                 maxCount = colorCount[index];
31             }
32         }
33         cout << maxStr << endl;
34     }
35     return 0;
36 }
37 
38 int search(string color[1000], int len, string str, int begin, int end)
39 {
40     for (int i = 0; i < len; i++) {
41         if (color[i] == str) {
42             return i;
43         }
44     }
45     return -1;
46 }
posted @ 2018-04-08 12:57  ImAz  阅读(261)  评论(0编辑  收藏  举报