|
| 1 | +//https://www.acmicpc.net/problem/12026 |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.Arrays; |
| 6 | + |
| 7 | +public class BOJ_S1_12026_BOJ거리 { |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + |
| 11 | + int N = Integer.parseInt(br.readLine()); |
| 12 | + int [] arr = new int[N]; |
| 13 | + int [][] dp = new int[N][3]; |
| 14 | + |
| 15 | + String str = br.readLine(); |
| 16 | + |
| 17 | + for (int i = 0; i < N; i++) { |
| 18 | + char c = str.charAt(i); |
| 19 | + |
| 20 | + if(c == 'O') arr[i] = 1; |
| 21 | + else if (c == 'J') arr[i] = 2; |
| 22 | + |
| 23 | + Arrays.fill(dp[i], Integer.MAX_VALUE); |
| 24 | + } |
| 25 | + |
| 26 | + dp[0][0] = 0; |
| 27 | + |
| 28 | + for (int i = 1; i < N; i++) { |
| 29 | + int now = arr[i]; |
| 30 | + int past = (now+2) % 3; |
| 31 | + |
| 32 | + for (int j = 0; j < i; j++) { |
| 33 | + if(arr[j] != past || dp[j][past] == Integer.MAX_VALUE) continue; |
| 34 | + |
| 35 | + int dist = (i-j)*(i-j); |
| 36 | + |
| 37 | + dp[i][now] = Math.min(dp[j][past] + dist, dp[i][now]); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + int ans = Integer.MAX_VALUE; |
| 42 | + |
| 43 | + for (int i = 0; i < 3; i++) { |
| 44 | + ans = Math.min(ans, dp[N-1][i]); |
| 45 | + } |
| 46 | + |
| 47 | + if(ans == Integer.MAX_VALUE) System.out.println(-1); |
| 48 | + else System.out.print(ans); |
| 49 | + } |
| 50 | +} |
0 commit comments