根据更高的分数(从0到800),从n个地区中的每个地区寻找和打印两个学生的独特团队(否则打印"?")
我认为我们可以跟踪最大和第二大元素,初始化分数为-1和-1。只有几种可能性:
但似乎这是错误的,但我不知道为什么?
代码:
import java.util.Arrays;
import java.util.Scanner;
public class B659 {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n = num();
int m = num();
String[] rgn1 = new String[m]; // students with highest score in their region
String[] rgn2 = new String[m]; // students with second-highest score in their region
int[] rgn1s = new int[m]; // highest score in the regions
int[] rgn2s = new int[m]; // second-highest score in the regions
Arrays.fill(rgn1s, -1);
Arrays.fill(rgn2s, -1);
boolean[] und = new boolean[m];
for (int i = 0; i < n; i++) {
String sn = str();
int r = num() - 1;
int sc = num();
if (sc > rgn1s[r]) {
if (rgn2s[r] == rgn1s[r] && rgn1s[r] != -1) {
und[r] = true;
continue;
} else {
rgn2s[r] = rgn1s[r];
rgn2[r] = rgn1[r];
}
rgn1s[r] = sc;
rgn1[r] = sn;
} else if (sc > rgn2s[r]) {
rgn2s[r] = sc;
rgn2[r] = sn;
} else if (sc == rgn2s[r]) {
und[r] = true;
}
}
for (int i = 0; i < m; i++) {
print((!und[i]) ? (rgn1[i] + " " + rgn2[i]) : "?");
}
}
private static int num() {
return sc.nextInt();
}
private static String str() {
return sc.next();
}
private static void print(Object x) {
System.out.println(x);
}
}
答案 0 :(得分:1)
一旦遇到重复值并且und[r]
字段设置为true,您的代码就无法处理这种情况,会遇到两个更高的值。
例如:
6 2
Ram 1 200
Shyam 1 200
Raju 2 200
丽塔1 300
赫拉2 500
Sita 1 500
你需要重新定义if,如果它们恰好是最后一对,那么如果重复条目的一部分,则需要添加另一个。
else if (sc == rgn1s[r]) {
und[r] = true;
}
例如:
6 2
Ram 1 200
Shyam 1 300
Raju 2 200
丽塔1 500
赫拉2 500
Sita 1 500