πŸ“– [λ°±μ€€μ•Œκ³ λ¦¬μ¦˜ 풀이] Q.11048 μ΄λ™ν•˜κΈ° 문제 풀이

πŸ“– 문제

https://www.acmicpc.net/problem/11048

πŸ” 접근법

Q.11048 μ΄λ™ν•˜κΈ° 문제 ν’€μ΄μž…λ‹ˆλ‹€.

미둜λ₯Ό μ΄λ™ν•˜λ©° N,M κΉŒμ§€ 이동할 λ•Œ κ°€μ Έμ˜¬ 수 μžˆλŠ” 사탕 개수의 μ΅œλŒ€κ°’μ„ κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

μ²˜μŒμ—λŠ” κ·Έλž˜ν”„ 탐색 μ•Œκ³ λ¦¬μ¦˜μΈ bfs , dfs λ₯Ό 톡해 μ ‘κ·Όν–ˆμœΌλ‚˜ μ΅œλ‹¨κ±°λ¦¬κ°€ μ•„λ‹Œ

μ΅œλŒ€ μ‚¬νƒ•μ˜ 개수λ₯Ό κ΅¬ν•˜κΈ° μœ„ν•΄ λ‹€λ₯Έ 경둜λ₯Ό 거쳐 온 κ²½μš°λ„ μ‚΄νŽ΄λ΄μ•Ό ν•˜κ³  경우의 μˆ˜κ°€ λ„ˆλ¬΄ λ§Žμ•˜μŠ΅λ‹ˆλ‹€.

그리고 λ―Έλ‘œμ— μž₯μ• λ¬Όκ³Ό 같은 λ°©ν•΄λ¬Ό 없이 였λ₯Έμͺ½, μ•„λž˜μͺ½, λŒ€κ°μ„  μ•„λž˜ λͺ¨λ“  경우둜

μ›€μ§μΌμˆ˜ μžˆμœΌλ―€λ‘œ λ™μ ν”„λ‘œκ·Έλž˜λ°μ„ 톡해 ν’€μ΄ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

r,c μœ„μΉ˜λ‘œ 올 λ•Œ λ°”λ‘œ μœ„μ—μ„œ μ˜€λƒ μ™Όμͺ½μ—μ„œ μ˜€λƒ λŒ€κ°μ„  μ™Όμͺ½ μœ„μ—μ„œ μ˜€λŠ” 경우 쀑 이미

κ°€μž₯ λ§Žμ€ 개수의 사탕을 ν™•λ³΄ν•œ μͺ½μ—μ„œ 였면 μ΅œλŒ€κ°’μ΄ λ©λ‹ˆλ‹€.

dp[i][j] = MAX(dp[i-1][j] , dp[i][j-1] , dp[i-1][j-1] ) + area[i][j]

κ·ΈλŸ¬λ‚˜ μ—¬κΈ°μ„œ λŒ€κ°μ„  κ²½μš°λŠ” λ³Ό ν•„μš”κ°€ μ—†κ²Œ λ©λ‹ˆλ‹€.

μ™œλƒν•˜λ©΄ 이미 μ‚¬νƒ•μ˜ κ°œμˆ˜λŠ” λͺ¨λ‘ 0κ°œμ΄μƒμ΄λ―€λ‘œ ꡳ이 λŒ€κ°μ„ μœΌλ‘œ λΉ λ₯΄κ²Œ λ‚΄λ € 갈 ν•„μš” 없이

였λ₯Έμͺ½μœΌλ‘œ μ΄λ™ν•˜κ³  μ•„λž˜λ‘œ μ΄λ™ν•˜λŠ” 것이 λŒ€κ°μ„ μœΌλ‘œ μ΄λ™ν•˜λŠ” 것보닀 λ§Žμ€ 개수의 사탕을 확보할 수 있기 λ•Œλ¬Έμž…λ‹ˆλ‹€.

κ·Έλž˜μ„œ κ²°κ΅­

dp[i][j] = MAX(dp[i-1][j] , dp[i][j-1]) + area[i][j]

μœ„μ™€ 같은 μ ν™”μ‹μœΌλ‘œ 닡을 λ„μΆœν•  수 μžˆμŠ΅λ‹ˆλ‹€.

πŸ’» μ½”λ“œ

package problem.dynamic;

import java.io.*;

public class Main_11048 {
    static int n;
    static int m;
    static int[][] area;
    static int dp[][];

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        input();
        solve();
        System.out.println(dp[n-1][m-1]);
        bw.flush();
        bw.close();
    }

    public static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String in[] = br.readLine().split(" ");
        n = Integer.parseInt(in[0]);
        m = Integer.parseInt(in[1]);

        area = new int[n][m];
        dp = new int[n][m];

        for (int i = 0; i < n; i++) {
            String temp[] = br.readLine().split(" ");
            for (int j = 0; j < m; j++) {
                int num = Integer.parseInt(temp[j]);
                area[i][j] = num;
            }
        }
    }

    public static void solve() {
        dp[0][0] = area[0][0];
        for(int i=1; i<n; i++){
            dp[i][0] = dp[i-1][0] + area[i][0];
        }
        for(int i=1; i<m; i++){
            dp[0][i] = dp[0][i-1] + area[0][i];
        }

        for(int i=1; i<n; i++){
            for(int j=1; j<m; j++){
                int maxNum = Math.max(dp[i-1][j] , dp[i][j-1] );
                dp[i][j] = maxNum+area[i][j];
            }
        }
    }
}

Written on January 11, 2021