HDU 1004 Let the Balloon Rise

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1004

Let the Balloon Rise

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

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

Author
WU, Jiazhi

Source
ZJCPC2004

Recommend
JGShining

大意——给你一堆有颜色的气球,让你统计什么颜色的气球数量最多,输出该颜色。

思路——首先将各个字符串进行字典序排序,然后统计各个字符串的个数及它们第一次出现的位置,位置及个数用结构体封装,最后对结构体数组按个数排序,最后根据个数最多的结构体的成员(位置)找到原字符串,并输出。

复杂度分析——时间复杂度:O(n),空间复杂度:O(n)

附上AC代码:


#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned int UI;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
const double PI = 3.14159265;
const double E = 2.71828182846;

struct node
{
	int cnt;
	int flag;
};

bool cmp(node a, node b);

int main()
{
	ios::sync_with_stdio(false);
	int n;
	while (cin >> n && n != 0)
	{
		string str[1000];
		node rank[1000];
		for (int i=0; i<n; i++)
		{
			cin >> str[i];
			rank[i].cnt = rank[i].flag = 0;
		}
		sort(str, str+n);
		int count = 0;
		rank[0].cnt = 1;
		rank[0].flag = 0;
		for (int i=1; i<n; i++)
		{
			if (str[i] != str[i-1])
			{
				rank[++count].cnt = 1;
				rank[count].flag = i;
			}
			else
				rank[count].cnt++;
		}
		sort(rank, rank+count+1, cmp);
		cout << str[rank[count].flag] << endl;
	}
	return 0;
}

bool cmp(node a, node b)
{
	return a.cnt < b.cnt;
}


你可能感兴趣的:(排序,HDU)