https://www.acmicpc.net/problem/1727
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int n, m;
static int[] manPersonality, womanPersonality;
static void input() {
Reader scanner = new Reader();
n = scanner.nextInt();
m = scanner.nextInt();
manPersonality = new int[n + 1];
womanPersonality = new int[m + 1];
for(int idx = 1; idx <= n; idx++)
manPersonality[idx] = scanner.nextInt();
for(int idx = 1; idx <= m; idx++)
womanPersonality[idx] = scanner.nextInt();
}
static void solution() {
Arrays.sort(manPersonality);
Arrays.sort(womanPersonality);
int[][] dp = new int[n + 1][m + 1];
for(int man = 1; man <= n; man++) {
for(int woman = 1; woman <= m; woman++) {
dp[man][woman] = dp[man - 1][woman - 1] + Math.abs(manPersonality[man] - womanPersonality[woman]);
if(man > woman)
dp[man][woman] = Math.min(dp[man][woman], dp[man - 1][woman]);
else if(man < woman)
dp[man][woman] = Math.min(dp[man][woman], dp[man][woman - 1]);
}
}
System.out.println(dp[n][m]);
}
public static void main(String[] args) {
input();
solution();
}
static class Reader {
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
남자 : 5 1 10 24
여자 : 2 6 12 30
남자 : 1 5 10 24
여자 : 2 6 12 30
dp[m][w] = m번째까지의 남자와 w번째까지의 여자를 매칭을 시켰을 때 성격 차이의 합의 최소값