Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions 유병규_16주차/[BOJ-1727] 커플 만들기.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import java.io.*;
import java.util.*;

public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());

int[] men = new int[n + 1];
int[] women = new int[m + 1];

st = new StringTokenizer(br.readLine());
for (int i=1; i<=n; i++) {
men[i] = Integer.parseInt(st.nextToken());
}

st = new StringTokenizer(br.readLine());
for (int i=1; i<=m; i++) {
women[i] = Integer.parseInt(st.nextToken());
}

// 정렬
Arrays.sort(men);
Arrays.sort(women);

// 작은 그룹과 큰 그룹 결정
int[] small, large;
int smallSize, largeSize;

if (n <= m) {
small = men;
large = women;
smallSize = n;
largeSize = m;
} else {
small = women;
large = men;
smallSize = m;
largeSize = n;
}

// DP 배열 초기화
long[][] dp = new long[smallSize+1][largeSize+1];

// 초기값 설정
for (int i=0; i<=smallSize; i++) {
for (int j=0; j<i; j++) {
dp[i][j] = Long.MAX_VALUE;
}
}

// DP 계산
for (int i=1; i<=smallSize; i++) {
for (int j=i; j<=largeSize; j++) {
if (j == i) {
dp[i][j] = dp[i-1][j-1] + Math.abs(small[i] - large[j]);
} else {
dp[i][j] = Math.min(
dp[i][j-1], // j번째 사람을 선택하지 않는 경우
dp[i-1][j-1] + Math.abs(small[i] - large[j]) // j번째 사람을 선택하는 경우
);
}
}
}
Comment on lines +55 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 j번째 사람을 선택하는 경우와 선택하지 않는 경우를 따로 처리하려고 dp 배열 두 개를 관리했는데 그럴 필요가 없었군요... 좋은 코드네요 👍


System.out.println(dp[smallSize][largeSize]);
}
}