|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 8 | + |
| 9 | + static int size, closeCnt, ans; |
| 10 | + static int dp[][][]; |
| 11 | + static int arr[][]; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + while(true) { |
| 15 | + init(); |
| 16 | + if (size == 0 && closeCnt ==0) break; |
| 17 | + process(); |
| 18 | + print(); |
| 19 | + } |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + private static void init() throws IOException { |
| 24 | + |
| 25 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 26 | + size = Integer.parseInt(st.nextToken()); |
| 27 | + closeCnt = Integer.parseInt(st.nextToken()); |
| 28 | + ans = 0 ; |
| 29 | + if (size == 0 )return; |
| 30 | + |
| 31 | + dp = new int [size][3][closeCnt+1]; |
| 32 | + // dp[i][j][k]: i번째칸까지 와서 k번만큼 방을 닫았을 때의 최댓값. 이때 j는 마지막에 어디를 닫았느냐를 의미 (0: 왼쪽, 1:오른쪽, 2:안닫음) |
| 33 | + arr = new int[size][2]; |
| 34 | + |
| 35 | + |
| 36 | + for (int i = 0; i < size; i++) { |
| 37 | + st = new StringTokenizer(br.readLine()); |
| 38 | + for (int j = 0; j < 2; j++) { |
| 39 | + arr[i][j] = Integer.parseInt(st.nextToken()); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | + } |
| 46 | + |
| 47 | + private static void process() { |
| 48 | + if (closeCnt != 0) { |
| 49 | + dp[0][0][1] = arr[0][1]; |
| 50 | + dp[0][1][1] = arr[0][0]; |
| 51 | + } |
| 52 | + |
| 53 | + dp[0][2][0] = arr[0][1] + arr[0][0]; |
| 54 | + |
| 55 | + for (int i = 1; i < size; i++) { |
| 56 | + for (int j = 0; j <= closeCnt; j++) { |
| 57 | + dp[i][2][j] = Math.max( Math.max(dp[i-1][0][j],dp[i-1][1][j] ), dp[i-1][2][j]); |
| 58 | + if (dp[i][2][j] != 0) dp[i][2][j] += arr[i][0] + arr[i][1]; |
| 59 | + |
| 60 | + if (j == 0) continue; |
| 61 | + dp[i][1][j] = Math.max(dp[i-1][1][j-1],dp[i-1][2][j-1]); |
| 62 | + if (dp[i][1][j] != 0) dp[i][1][j] += arr[i][0]; |
| 63 | + |
| 64 | + dp[i][0][j] = Math.max(dp[i-1][0][j-1],dp[i-1][2][j-1]); |
| 65 | + if (dp[i][0][j] != 0) dp[i][0][j] += arr[i][1]; |
| 66 | + |
| 67 | + } |
| 68 | + } |
| 69 | + System.out.println(dp[size-1][0][closeCnt] + " " + dp[size-1][1][closeCnt] + " " + dp[size-1][2][closeCnt]); |
| 70 | + ans = Math.max( Math.max(dp[size-1][0][closeCnt],dp[size-1][1][closeCnt]),dp[size-1][2][closeCnt]); |
| 71 | + |
| 72 | + } |
| 73 | + |
| 74 | + |
| 75 | + private static void print() { |
| 76 | + System.out.println(ans); |
| 77 | + } |
| 78 | +} |
| 79 | +``` |
0 commit comments