|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.BufferedWriter; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.io.OutputStreamWriter; |
| 7 | + |
| 8 | +public class BJ_1285_동전_뒤집기 { |
| 9 | + |
| 10 | + private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + |
| 13 | + private static int N; |
| 14 | + private static int ans; |
| 15 | + private static int[] coins; |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + init(); |
| 19 | + sol(); |
| 20 | + } |
| 21 | + |
| 22 | + private static void init() throws IOException { |
| 23 | + N = Integer.parseInt(br.readLine()); |
| 24 | + ans = Integer.MAX_VALUE; |
| 25 | + |
| 26 | + coins = new int[N]; |
| 27 | + for (int i = 0; i < N; i++) { |
| 28 | + String s = br.readLine(); |
| 29 | + for (int j = 0; j < N; j++) { |
| 30 | + if (s.charAt(j) == 'T') { |
| 31 | + coins[i] += (1 << j); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private static void sol() throws IOException { |
| 38 | + // 행 뒤집기 |
| 39 | + for (int rowFillped = 0; rowFillped < (1 << N); rowFillped++) { |
| 40 | + // 뒷면 |
| 41 | + int totalTails = 0; |
| 42 | + |
| 43 | + for (int row = 0; row < N; row++) { |
| 44 | + // 0일 때 뒤집지 않고(0), 1일 때 뒤집을 때(1) 0이 되어야 해서 XOR 연산 |
| 45 | + int tailsInCol = Integer.bitCount(coins[row] ^ rowFillped); |
| 46 | + totalTails += Math.min(tailsInCol, N - tailsInCol); |
| 47 | + } |
| 48 | + ans = Math.min(ans, totalTails); |
| 49 | + } |
| 50 | + |
| 51 | + bw.write(ans + ""); |
| 52 | + bw.flush(); |
| 53 | + bw.close(); |
| 54 | + br.close(); |
| 55 | + } |
| 56 | + |
| 57 | + private static int countTails(boolean[][] arr) { |
| 58 | + int cnt = 0; |
| 59 | + for (int i = 0; i < N; i++) { |
| 60 | + for (int j = 0; j < N; j++) { |
| 61 | + if (arr[i][j]) { |
| 62 | + cnt++; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + return cnt; |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
0 commit comments