import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt(); //the number of test cases
for(int tc = 1; tc <= T; tc++) {
int N = in.nextInt(); // the number of the students
int Kmin = in.nextInt();
int Kmax = in.nextInt();
int[] scores = new int[1001];
int Smin = 100; //the min score
int Smax = 1; //the max score
for(int i = 0; i < N; i++) {
scores[i] = in.nextInt();
if(scores[i] > Smax) {
Smax = scores[i];
}
if(scores[i] < Smin) {
Smin = scores[i];
}
}
int result = 1000;
for(int T1 = Smin; T1 < Smax; T1++) {
for(int T2 = Smax; T2 > Smin; T2--) {
int[] nums = new int[3]; //the numbers of Class A, B, C
boolean flag = true;
for(int j = 0; j < N; j++) {
if(scores[j] >= T2) {
nums[0]++; //the num of Class A
if(nums[0] > Kmax) {
flag = false;
break;
}
}else if(scores[j] < T1) {
nums[2]++; //the num of Class C
if(nums[2] > Kmax) {
flag = false;
break;
}
}else {
nums[1]++;
if(nums[1] > Kmax) {
flag = false;
break;
}
}
}
for(int x = 0; x < 3; x++) {
if(nums[x] < Kmin) {
flag = false;
}
}
if(flag) {
sort(nums);
int temp = nums[2] - nums[0];
if(temp < result) {
result = temp;
}
}
}
}
if(result == 1000) {
result = -1;
}
System.out.println("#"+tc+" "+result);
}
}
public static void sort(int[] array) {
int length = array.length;
for(int i = 0; i < length; i++) {
for(int j = i+1; j < length; j++) {
if(array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}
分班规则:
1)如果分数>=T2, 那么该学生会被分配到A班;
2)如果分数>=T1&&<T2,那么该学生会被分配到B班;
3)如果分数<T1,则该学生会被分配到C班。
4)每班的最小人数不能低于Kmin(>=Kmin),最大人数不能大于Kmax(<=Kmax)
现在,在T1,T2没有给定的情况下,给出要分班的学生的分数,要求按照分配规则来分班,并求出人数最多的班与人数最少的班的人数差异,如果有多种可能,则求其最小值,若无法按照规则分配,则输出-1。
输入要求:
1)第一行,输入T,表示有T个测试案例
2)第二行开始,输入每个测试案例,其中每个案例,第一行输入三个数,N代表学生的人数(1-1000), Kmin代表每个班人数的下限,Kmax代表每个班的人数上限
3)输入学生的分数(1-100)
输出要求:
输出(#+test_cast+" "+result)
思路:
题目中,分班的界定T1, T2并未知,因此可能有多种可能。我们可以找出学生中的最高分与最低分,以此为界限,不断去找可能的T1, T2,并检查每班的人数是否符合要求,如果符合,则与当前的result比较,找出更贴合题目要求的值。其中找出最高分与最低分,一种很直观的做法就是把分数(int[] scores)排序,那么scores[0]即为最低分,scores[N-1]即为最高分。另一种做法就是,先设定一个特别的最高分与最低分,在输入学生分数的时候,不断与当前的最高分与最低分作比较,并适时更新。
来源:https://www.cnblogs.com/WakingShaw/p/12636329.html