BOJ::2169 로봇 조종하기

시사점

이해(10)

설계, 손 코딩(37)

시간 복잡도

공간 복잡도

손 코딩 후 문제 리뷰(x)

구현(33)

함수 List

업데이트 되는 변수

실제 구현

#include<bits/stdc++.h>
#define endl '\n'
#define rep(i,a,b) for(int i=a;i<b;i++)
#define r_rep(i,a,b) for(int i=a;i>b;i--)
const int MAXNM = 1000;
const int INF = 987654321;
using namespace std;

int n, m;
int a[MAXNM][MAXNM];
int dp[MAXNM][MAXNM];

void solve(){
    /* 0 행 : 우측 방향만 존재 */
    dp[0][0] = a[0][0];
    int accum = a[0][0];
    rep(j, 1, m){
        dp[0][j] = a[0][j] + accum;
        accum += a[0][j];
    }

    /* [1, n-2]행 : 좌 우 모두 존재 */
    rep(i, 1, n-1){
        rep(pos, 0, m){
            int mx = -1 * INF;
            accum = 0;

            r_rep(j, pos-1, -1){
                int sum = dp[i-1][j] + a[i][j] + accum;
                mx = max(mx, sum);
                accum += a[i][j];
            }
            accum = 0;
            rep(j, pos+1, m){
                int sum = dp[i-1][j] + a[i][j] + accum;
                mx = max(mx, sum);
                accum += a[i][j];
            }
            dp[i][pos] = max(mx , dp[i-1][pos]) + a[i][pos];
        }
    }


    /* n-1행 : 우측 방향만 존재 */
    if(n > 1){
        rep(pos, 0, m){
            int row = n-1;
            int mx = -1 * INF;
            accum = 0;
            r_rep(j, pos-1, -1){
                int sum = dp[row-1][j] + a[row][j] + accum;
                mx = max(mx, sum);
                accum += a[row][j];
            }
            dp[row][pos] = max(mx , dp[row-1][pos]) + a[row][pos];
        }
    }

}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> n>> m;
    rep(i, 0, n) rep(j, 0, m) cin >> a[i][j];

    solve();

    cout << dp[n-1][m-1] << endl;
    return 0;
}

구현 후 코드리뷰 + 예제 돌려보기(x)

디버깅(x)

좋은 코드

void solve(){
    /* 0 행 : 우측 방향만 존재 */
    dp[1][1] = a[1][1];
    int accum = a[1][1];
    rep(j, 2, m+1){
        dp[1][j] = a[1][j] + accum;
        accum += a[1][j];
    }

    int tmp[2][MAXNM+1]={0};
    rep(i, 2, n+1){
        tmp[0][0] = dp[i-1][1];
        rep(j, 1, m+1) tmp[0][j] = max(tmp[0][j-1], dp[i-1][j]) + a[i][j];

        tmp[1][m+1] = dp[i-1][m];
        r_rep(j, m, 0) tmp[1][j] = max(tmp[1][j+1], dp[i-1][j]) + a[i][j];

        rep(j, 1, m+1) dp[i][j] = max(tmp[0][j], tmp[1][j]);
    }

}

최적화