Java 篮球比赛球员分组算法:最大能力值优先选择
import java.util.Arrays; import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); // 球员人数 int m = scanner.nextInt(); // 一次挑选的左右各人数 int[] abilities = new int[n]; // 球员能力值数组 for (int i = 0; i < n; i++) { abilities[i] = scanner.nextInt(); }
char[] teams = new char[n]; // 存放球员所属队伍,'A' 表示第一个队伍,'B' 表示第二个队伍
Arrays.fill(teams, ' '); // 初始化为空
int coach = 0; // 0 表示第一个教练,1 表示第二个教练
int left = n; // 剩余球员数量
int maxIndex; // 能力值最大球员的索引
while (left > 0) {
maxIndex = findMaxIndex(abilities); // 找到能力值最大球员的索引
teams[maxIndex] = (coach == 0) ? 'A' : 'B'; // 将该球员分配给当前教练的队伍
left--; // 剩余球员数量减一
// 移除选中球员及其左右两侧的球员
int start = Math.max(0, maxIndex - m); // 左侧起始位置
int end = Math.min(n - 1, maxIndex + m); // 右侧结束位置
for (int i = start; i <= end; i++) {
abilities[i] = -1; // 将选中球员的左右两侧的球员能力值标记为 -1,表示已被选中
}
coach = (coach + 1) % 2; // 切换教练
}
String result = new String(teams); // 将球员所属队伍数组转换为字符串
System.out.println(result); // 输出结果
}
private static int findMaxIndex(int[] array) {
int maxIndex = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] > array[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
}
原文地址: https://www.cveoy.top/t/topic/byen 著作权归作者所有。请勿转载和采集!