반응형

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { StringBuilder sb = new StringBuilder(); int n; int[][] stat; boolean[] visit; int[] a; int[] b; int result = Integer.MAX_VALUE; public void solution() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; n = Integer.parseInt(br.readLine()); stat = new int[n][n]; visit = new boolean[n]; a = new int[n/2]; b = new int[n/2]; for(int i=0; i<n; i++){ st = new StringTokenizer(br.readLine()); for(int j=0; j<n; j++){ stat[i][j] = Integer.parseInt(st.nextToken()); } } dfs(0, 0); System.out.println(result); } public void dfs(int index,int depth){ if(depth==n/2){ int index_a = 0,index_b = 0; for(int i=0; i<n; i++){ if(visit[i]){ a[index_a++] = i; }else{ b[index_b++] = i; } } result = Math.min(result, Math.abs(cal(a)-cal(b))); } for(int i=index; i<n; i++){ if(!visit[i]){ visit[i] = true; dfs(i+1, depth+1); visit[i] = false; } } } public int cal(int[] numArray){ int result = 0; for(int i=0; i<numArray.length; i++){ for(int j=i+1; j<numArray.length; j++){ result += stat[numArray[i]][numArray[j]] + stat[numArray[j]][numArray[i]]; } } return result; } public static void main(String args[]) throws IOException { new Main().solution(); } }
먼저 dfs 재귀 함수를 통해 n의 숫자 만큼의 모든 경우의 수를 출력하고, 출력이 확인 된 후에 그 숫자 팀을 나누는 로직을 추가하고, 그 후 능력치를 팀별로 계산 하는 함수를 만든다. 그리고 그 능력치의 최소 값을 비교해 가장 낮은 숫자를 찾아낸 다음에 출력하는 식으로 순차적으로 풀었다.
반응형
'개발 > 알고리즘' 카테고리의 다른 글
백준 2529번 : 부등호 (0) | 2023.01.16 |
---|---|
백준 15661번 : 링크와 스타트 (0) | 2023.01.16 |
백준 1759번 : 암호 만들기 (0) | 2023.01.15 |
백준 14501번 : 퇴사 (0) | 2023.01.11 |
백준 18290번 : NM과 K (1) (0) | 2023.01.10 |