原题链接:PAT Ranking
1. 题意
有n个考场,每个考场有k个学生,给出学生的准考证号和分数
要求将所有学生按分数从高到底进行排名,分数相同的按准考证号排名
依次输出学生的准考证号,总排名,考场号,所在考场排名
2. 思路
首先肯定将学生包装成学生类,将这些属性填入
然后最关键的地方在于考场排名和总排名
这里我使用的办法是对每个考场进行排序,得到学生的local_rank
最后再将所有人排序,得到final_rank
使用Java会卡最后一个测试点。
3. 代码
仅供参考,过不了最后一个点,同样的方法C++能过
package adv1025;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
static class Stu implements Comparable<Stu>{
String id;
int score;
int finalRank;
int locationNumber;
int localRank;
public Stu(String id, int score, int locationNumber) {
this.id = id;
this.score = score;
this.locationNumber= locationNumber;
}
@Override
public int compareTo(Stu o) {
if (score == o.score) {
return id.compareTo(o.id);
} else if (score > o.score) {
return -1;
} else {
return 1;
}
}
@Override
public String toString() {
return id + " " + finalRank + " " + locationNumber + " " + localRank;
}
}
public static void main(String[] args) {
Scanner read = new Scanner(new BufferedInputStream(System.in));
List<Stu> total = new ArrayList<Stu>();
int n = read.nextInt();
for (int i = 1; i <= n; i++) {
int k = read.nextInt();
List<Stu> list = new ArrayList<Stu>();
for (int j = 1; j <= k; j++) {
Stu stu = new Stu(read.next(), read.nextInt(), i);
list.add(stu);
total.add(stu);
}
Collections.sort(list);
// 设第一名Rank为1, 遍历后面的学生, 成绩不同则rank=前面的同学+1
list.get(0).localRank = 1;
for (int j = 1; j < list.size(); j++) {
if (list.get(j-1).score == list.get(j).score) {
list.get(j).localRank = list.get(j-1).localRank;
} else {
list.get(j).localRank = j+1;
}
}
}
Collections.sort(total);
total.get(0).finalRank = 1;
System.out.println(total.size() + "\n" + total.get(0));
for (int i = 1; i < total.size(); i++) {
if (total.get(i-1).score == total.get(i).score) {
total.get(i).finalRank = total.get(i-1).finalRank;
} else {
total.get(i).finalRank = i + 1;
}
System.out.println(total.get(i));
}
}
}
测试图: