Skip to content

[BOJ/골드5] 22-10-17 (내려가기)#40

Merged
hyesuuou merged 1 commit into
mainfrom
hyesu
Oct 17, 2022
Merged

[BOJ/골드5] 22-10-17 (내려가기)#40
hyesuuou merged 1 commit into
mainfrom
hyesu

Conversation

@hyesuuou

Copy link
Copy Markdown
Collaborator

🌱 문제번호와 링크

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

🥺 무엇을 알게 되었나요?

처음에 2차원 배열 dp를 두개(max, min)만들어서 모든 값을 메모이제이션 했더니 메모리 초과가 났다.

import sys
input = sys.stdin.readline

n = int(input())

maxdp = [[0]*3 for _ in range(n)]
mindp = [[0]*3 for _ in range(n)]

score = []

for _ in range(n):
    a, b, c = map(int, input().split())
    score.append((a, b, c))


for i in range(n):
    for j in range(3):
        if j == 0:
            maxdp[i][j] = max(maxdp[i-1][0], maxdp[i-1][1]) + score[i][j]
            mindp[i][j] = min(mindp[i-1][0], mindp[i-1][1]) + score[i][j]
        elif j == 2:
            maxdp[i][j] = max(maxdp[i-1][1], maxdp[i-1][2]) + score[i][j]
            mindp[i][j] = min(mindp[i-1][1], mindp[i-1][2]) + score[i][j]
        else:
            maxdp[i][j] = max(maxdp[i-1]) + score[i][j]
            mindp[i][j] = min(mindp[i-1]) + score[i][j]

print(max(maxdp[n-1]), min(mindp[n-1]))

문제를 잘 읽어보면 메모리 제한이 4mb로 매우 적은 양이다. ..
그럼 저렇게 배열을 만들면 안된다는 건데,,
이 문제는 조금만 더 생각해보면 사실 옛날값까지 가지고 있을 필요가 없다.
그래서 굳이 2차원 배열로 모든 값을 저장하고 있지 않아도 된다.
그래서 현재 값만 maxdp, mindp에 저장해주는 걸로 바꿨다.

maxdp = [0, 0, 0]
mindp = [0, 0, 0]

그리고 for문을 돌면서 현재 가장 큰값, 현재 가장 작은 값을 저 배열에 저장해줬다!

tmp배열을 만든 이유는 바로바로 maxdp, mindp에 저장해버리면 만약 0번째 자리 -> 1번째자리 계산하게 되면 0번째자리가 이미 갱신되어버린 값이기 때문에 1번째자리 값이 제대로 안나온다, , ,, 그렇기 때문에 한 줄이 모두 끝나고 나서야 값을 갱신해줘야 한다! 이때 한 줄이 끝날때까지 임시 저장소를 가지고 있으려고 tmp배열을 사용했다.

@hyesuuou hyesuuou self-assigned this Oct 17, 2022
@hyesuuou hyesuuou merged commit c08ef8d into main Oct 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant