1 题目
2 代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class A1055 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int N = Integer.parseInt(input[0]);
int K = Integer.parseInt(input[1]);
ArrayList<Richest> totalRichest = new ArrayList<>();
for (int i = 0; i < N; i++) {
String[] line = br.readLine().split(" ");
totalRichest.add(new Richest(line[0], Integer.parseInt(line[1]), Integer.parseInt(line[2])));
}
for (int i = 0; i < K; i++) {
String[] line = br.readLine().split(" ");
int ageMin = Integer.parseInt(line[1]);
int ageMax = Integer.parseInt(line[2]);
ArrayList<Richest> richest = new ArrayList<>();
for (Richest r : totalRichest) {
if (r.getAge() >= ageMin && r.getAge() <= ageMax)
richest.add(r);
}
System.out.println("Case #" + (i + 1) + ":");
if (richest.size() == 0) {
System.out.println("None");
} else {
Collections.sort(richest, new Comparator<Richest>() {
@Override
public int compare(Richest o1, Richest o2) {
if (o1.getMoney() != o2.getMoney())
return o2.getMoney() - o1.getMoney();
else if (o1.getAge() != o2.getAge())
return o1.getAge() - o2.getAge();
else
return o1.getName().compareTo(o2.getName());
}
});
int num = Integer.parseInt(line[0]) > richest.size() ? richest.size() : Integer.parseInt(line[0]);
for (int j = 0; j < num; j++) {
System.out.println(richest.get(j).getName() + " " + richest.get(j).getAge() + " " + richest.get(j).getMoney());
}
}
}
}
}
class Richest {
private String name;
private int age;
private int money;
public Richest(String name, int age, int money) {
this.name = name;
this.age = age;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
3 要点
(1)思路:首先将所有富人的信息保存到totalList中,然后按照查询的要求,对年龄进行筛选,满足条件的富人添加到一个List中。然后,如果List的长度为0,输出None;反之,按照worth、age、name依次对List进行排序,最后按要求输出即可。
(2)依旧存在运行超时的测试点。