唉,虽然hdu1004是一个大水题,不过也毕竟是写的一个晚上的,发上来纪念一下吧%>_<%
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.
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.
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
import java.io.BufferedInputStream;
import java.util.Scanner;
/**
* 水题
* @author linyh
* @problemID hd1004
* @problemUrl http://acm.hdu.edu.cn/showproblem.php?pid=1004
*/
public class Main {
//private static final MAP_LENGTH=1024;
public static void main(String[] args) {
@SuppressWarnings("unused")
Main a=new Main();
}
public Main() {
final int MAP_LENGTH=1<<10;
Scanner cin=new Scanner(new BufferedInputStream(System.in));
while(cin.hasNext()){
// 存放气球以及气球个数
Balloon balloon[]=new Balloon[MAP_LENGTH];
// 输入总数
int n=cin.nextInt();
if(n==0) break;
for(int i=0;i<n;i++){
String s=cin.next();
// 根据哈希值计算存放位置
int position=s.hashCode()&(MAP_LENGTH-1);
if(balloon[position]!=null){
balloon[position].expand();
}else{
balloon[position]=new Balloon(s);
}
}
// 统计数量最多的
int maxIndex=0;
for(int i=1;i<MAP_LENGTH;i++){
if(balloon[maxIndex]==null
||balloon[i]!=null
&&balloon[i].getCount()>balloon[maxIndex].getCount()
){
maxIndex=i;
}
}
// 输出结果
System.out.println(balloon[maxIndex].getColor());
}
cin.close();
}
class Balloon{
private int count=1;
private String color;
public Balloon(String name) {
this.color=name;
}
public void expand() {
this.count++;
}
public int getCount() {
return this.count;
}
public String getColor() {
return this.color;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Balloon) {
Balloon b = (Balloon) obj;
if(this.color.equals(b.color)){
return true;
}
}
return false;
}
@Override
public int hashCode() {
return color.hashCode();
}
@Override
public String toString() {
return color+" "+count;
}
}
}
使用了hash计算存储位置。
1
|
int
position=s.hashCode()&(MAP_LENGTH-
1
);
|
最关键的就是这么一句。