dfs 알고리즘 문제이다.
이 문제는 스타트와 링크 문제와 매우 비슷하다.
그 전에는 팀 인원을 반으로 나눈다면
이번 문제는 "두 팀의 인원수는 같지 않아도 되지만, 한 명 이상이어야 한다." 라는 차이가 있다.
나머지 알고리즘 부분은 위의 링크에서 설명했으므로 달라진 부분만 보자.
일단 인원수는 (1명, N-1명
), (2명, N-2명
) ... (N-1명, 1명
) 이런 식으로 나눠질 수 있다.
teamA
에 속할 인원 수를 1
명에서 점차 N-1
명으로 늘려나가면서 최소의 차이를 구하면 된다.
코드의 주석을 보면서 설명하겠다.
package codingTestFiles.code;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class bj14889 {
public static int N;
// teamA에 속할 인원 수를 전역 변수 T로 선언
public static int T;
public static int MIN;
public static int[] teamA;
public static boolean[] visited;
public static int[][] ability;
public static void main(String[] args) throws Exception {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
ability = new int[N][N];
visited = new boolean[N];
for (int i = 0; i < N; i++) {
String line = br.readLine();
String[] split = line.split(" ");
for (int j = 0; j < N; j++) {
int score = Integer.parseInt(split[j]);
ability[i][j] = score;
MIN += score;
}
}
// T를 1부터 N-1까지 늘려나가면서 최소값을 구한다.
for (T = 1; T < N; T++) {
teamA = new int[T];
dfs(0, 0);
}
bw.write(MIN + "");
bw.flush();
bw.close();
br.close();
}
public static void dfs(int depth, int index) {
// teamA에 뽑은 인원 수가 T가 되면 종료한다.
if (depth == T) {
// 총 인원수 N명 중 teamA에 속하지 않은 인원을 teamB에 뽑는다.
List<Integer> teamBList = new ArrayList<>();
for (int i = 0; i < N; i++) {
if (!visited[i]) {
teamBList.add(i);
}
}
Object[] teamB = teamBList.toArray();
// 각 팀의 능력 합을 구한다.
int sumA = 0;
int sumB = 0;
// teamA는 인원수가 T이다.
for (int i = 0; i < T; i++) {
for (int j = 0; j < T; j++) {
sumA += ability[teamA[i]][teamA[j]];
}
}
// teamB의 인원수는 전체 N 명에서 teamA에 속한 인원수 T를 뺀 N - T 명이다.
for (int i = 0; i < N - T; i++) {
for (int j = 0; j < N - T; j++) {
sumB += ability[(int) teamB[i]][(int) teamB[j]];
}
}
MIN = Math.min(MIN, Math.abs(sumA - sumB));
return;
}
for (int i = index; i < N; i++) {
if (!visited[i]) {
visited[i] = true;
teamA[depth] = i;
dfs(depth + 1, i);
visited[i] = false;
}
}
}
}
참고 : 전의 포스트에서도 설명했지만
i
번째 인원을 뽑고 다음 인원을 뽑을때는i + 1
번째 부터 보면 된다. 이 사항을 고려하지 않으면 시간 초과가 발생한다.