DAMPER's 낙서장

[ALGOSPOT] TRIANGLEPATH 본문

Problem Solving/알고리즘 문제해결전략

[ALGOSPOT] TRIANGLEPATH

DAMPER 2020. 10. 15. 12:31
728x90

algospot.com/judge/problem/read/TRIANGLEPATH

 

algospot.com :: TRIANGLEPATH

삼각형 위의 최대 경로 문제 정보 문제 6 1 2 3 7 4 9 4 1 7 2 7 5 9 4 위 형태와 같이 삼각형 모양으로 배치된 자연수들이 있습니다. 맨 위의 숫자에서 시작해, 한 번에 한 칸씩 아래로 내려가 맨 아래 ��

algospot.com

 

<아이디어>

밑으로 1층씩 내려가면서 바로 밑 자리 최대값 갱신, 오른쪽 아래 최대값 갱신으로 저장.

 

<구현>

아이디어 그대로 구현(?) 하면 된다.

 

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
#include <bits/stdc++.h>
using namespace std;
#define swap(a,b) (a)^=(b)^=(a)^=(b)
#define endl '\n'
typedef long long lld;
 
int main()
{
    ios_base::sync_with_stdio(NULL);
    cin.tie(NULL);
    cout.tie(NULL);
    int tc; cin>>tc;
    while(tc--)
    {
        int n;
        cin>>n;
        vector<vector<int>> v(n, vector<int> (n)), dp(n, vector<int> (n, 0));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<=i;j++)
                cin>>v[i][j];
        }
        dp[0][0= v[0][0];
        for(int i=0;i<n-1;i++)
        {
            for(int j=0;j<=i;j++)
            {
                dp[i+1][j] = max(dp[i+1][j], dp[i][j]+v[i+1][j]);
                dp[i+1][j+1= max(dp[i+1][j+1], dp[i][j]+v[i+1][j+1]);
            }
        }
        int mx = dp[n-1][0];
        for(int i=0;i<n;i++)
            mx = max(mx, dp[n-1][i]);
        cout<<mx<<endl;
    }
    return 0;
}
cs

 

다음 소스코드는 책을 보고 참고한 코드입니다.

 

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
#include <bits/stdc++.h>
using namespace std;
#define swap(a,b) (a)^=(b)^=(a)^=(b)
#define endl '\n'
typedef long long lld;
 
int n, triangle[101][101];
int cache[101][101];
 
int path(int y, int x)
{
    if(y==n-1return triangle[y][x];
    int& ret = cache[y][x];
    if(ret!=0return ret;
    return ret = max(path(y+1, x+1), path(y+1, x))+triangle[y][x];
}
 
int main()
{
    ios_base::sync_with_stdio(NULL);
    cin.tie(NULL);
    cout.tie(NULL);
    int tc;
    cin>>tc;
    while(tc--)
    {
        cin>>n;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<=i;j++)
                cin>>triangle[i][j];
        }
        cout<<path(00)<<endl;
    }
    return 0;
}
cs
728x90