본문 바로가기

기타[etc]/알고리즘

[알고리즘] DP- 땅따먹기

SMALL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<vector>
using namespace std;
 
 
vector<vector<int>> dp(10001vector<int>(4,0));
 
int hopscotch(vector<vector<int> > board)
{
    // 함수를 완성하세요.
    
    // if (x != z)
    // d[n][x] = max(d[n-1][z]) + board[n][z] 
    // 점화식[?]
 
    int answer = 0;
    int col =  4;
      int row = board.size();
    int tmp = 0;
  for(int i = 0 ; i < 4; i++)
        dp[0][i] = board[0][i];
 
  for (int y = 1 ; y < row ;y++ )
  {
            for ( int x = 0 ; x < col ;x++)
            {
                tmp = 0;
                for(int z = 0 ; z < col ; z++)
                {
                    //구하고자 하는 이전 합의 최댓값 
                    if(x != z){
                        if( tmp < dp[y-1][z])
                            tmp = dp[y-1][z];
                    }
                }
                dp[y][x] = tmp + board[y][x];
            }
    }
 
/* Debug
    for (int i = 0 ; i < row; i++)
    {
        for( int x= 0 ; x < 4; x++)
        {
            cout << dp[i][x] << ' ';
        }
        cout << endl;
    }
*/
 
    for(int i = 0 ; i < 4;i++)
    {
            if(answer < dp[row-1][i])
            answer = dp[row-1][i];
    }
 
    return answer;
}
 
int main()
{
    vector<vector<int> > test{
                                                        {1,2,3,5},
                                                        {13,6,7,8},     //  10    9  12 11
                                                        {4,3,5,1},     // 16    15 13 13
                                                        {8,1,2,3},  // 1015  17 18 19
                                                        {10,2,2,3},  // 2019
                                                        {1,8,2,3}};
 //아래는 테스트로 출력해 보기 위한 코드입니다.
    cout << hopscotch(test);
}
 
cs
LIST