코딩
알고스팟 자바(java) 해답 : QUANTIZE
King Attila
2021. 5. 14. 07:44
728x90
import java.util.*;
public class Main{
static int[][] cache;
static int[] map;
static int result;
static int n;
static int s;
public static void main(String args[]) throws Exception {
int testcase;
cache = new int[101][101];
Scanner scanner = new Scanner(System.in);
testcase = scanner.nextInt();
for(int i = 0; i < testcase; i++){
result = 0x7fffffff;
for(int j = 1; j <= 100; j++)
Arrays.fill(cache[j], -1);
n = scanner.nextInt();
map = new int[n+1];
s = scanner.nextInt();
for(int j = 1; j <= n; j++)
map[j] = scanner.nextInt();
Arrays.sort(map);
if(s > n)
result = Math.min(result, search(1, 1, n-1));
else
result = Math.min(result, search(1, 1, s-1));
System.out.println(result);
}
}
static int search(int a, int b, int s){
int ret = 0x7fffffff;
if(cache[a][s] != -1)
return cache[a][s];
if(s == 0){
int temp = 0;
int calc = 0;
for(int j = a; j <= n; j++){
temp += map[j];
}
temp = (int)(0.5 + (double)temp / (n - a + 1));
//temp = temp / (n-a+1);
for(int j = a; j <= n; j++){
calc += (map[j] - temp) * (map[j] - temp);
}
return calc;
}
for(int i = b; i <= n-s; i++){
int temp = 0;
int calc = 0;
for(int j = a; j <= i; j++){
temp += map[j];
}
temp = (int) (0.5 + (double)temp / (i - a + 1));
//temp = temp / (i-a+1);
for(int j = a; j <= i; j++){
calc += (map[j] - temp) * (map[j] - temp);
}
ret = Math.min(ret, calc + search(i + 1, i + 1, s-1));
}
cache[a][s] = ret;
return ret;
}
}
728x90