티스토리 뷰
출저 : https://www.acmicpc.net/problem/14889
"비트마스크도 쓸수 있고, 그냥 DFS 로 짝지어서 할 수도 있고"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; class Main { static int N; static int[][] map; static boolean[] team; static int min = Integer.MAX_VALUE; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); map = new int[N][N]; team = new boolean[N]; for (int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for (int j = 0; j < N; j++) { map[i][j] = Integer.parseInt(st.nextToken()); } } solve(0,0); System.out.println(min); } static void solve(int cnt, int cur) { if(cnt == N/2) { int sumA = 0; int sumB = 0; for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { if(team[i] != team[j]) continue; if(team[i]) { sumA += map[i][j] + map[j][i]; } else { sumB += map[i][j] + map[j][i]; } } } min = Math.min(min, Math.abs(sumA-sumB)); return; } for (int i = cur; i < N; i++) { team[i] = true; solve(cnt+1,i+1); team[i] = false; } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 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; static int[][] map; static boolean[] team; static int min = Integer.MAX_VALUE; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); map = new int[N][N]; team = new boolean[N]; for (int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for (int j = 0; j < N; j++) { map[i][j] = Integer.parseInt(st.nextToken()); } } for (int i = 0; i < (1 << N); i++) { for (int j = 0; j < N; j++) { if( (i & ( 1 << j)) != 0) { team[j] = true; } } solve(); Arrays.fill(team, false); } System.out.println(min); } static void solve() { int[] sum = new int[2]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if(i == j || team[i] != team[j]) continue; if(team[i]) { sum[0] += map[i][j]; } else { sum[1] += map[i][j]; } } } min = Math.min(min, Math.abs(sum[0]-sum[1])); } } | cs |
'Study > 알고리즘 문제풀이' 카테고리의 다른 글
백준 9205. 맥주 마시면서 걸어가기 :: 돼지개발자 (0) | 2019.01.16 |
---|---|
백준 1592. 영식이와 친구들 :: 돼지개발자 (0) | 2019.01.16 |
SWEA 1868. 파핑파핑 지뢰찾기 :: 돼지개발자 (0) | 2019.01.14 |
백준 1783. 병든 나이트 :: 돼지개발자 (0) | 2019.01.14 |
백준 3055. 탈출 :: 돼지개발자 (0) | 2019.01.10 |
댓글
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday