Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create test.md #24

Closed
wants to merge 1 commit into from
Closed

Create test.md #24

wants to merge 1 commit into from

Conversation

Munbin-Lee
Copy link
Member

늦게 올려봅니당

🔗 문제 링크

DP 를 정말 오랜만에 봐서 DP 의 정석같은 문제를 풀었습니다.
정수 삼각형

✔️ 소요된 시간

30분
DP 가 그냥 오랜만이라서 DP 자체를 상기하느라 그렇지 문제 푸는 시간은 오래 안걸렸어요.

image

위 그림은 크기가 5인 정수 삼각형의 한 모습이다.

맨 위층 7부터 시작해서 아래에 있는 수 중 하나를 선택하여 아래층으로 내려올 때, 이제까지 선택된 수의 합이 최대가 되는 경로를 구하는 프로그램을 작성하라. 아래층에 있는 수는 현재 층에서 선택된 수의 대각선 왼쪽 또는 대각선 오른쪽에 있는 것 중에서만 선택할 수 있다.

삼각형의 크기는 1 이상 500 이하이다. 삼각형을 이루고 있는 각 수는 모두 정수이며, 범위는 0 이상 9999 이하이다.

✨ 수도 코드

  1. i 를 1 부터 N 까지 반복한다. (N 층)
  2. j 를 1 부터 i 까지 반복한다. (맨위층 1 개, 그 다음 층 2개 .... 1층 N 개니깐)
  3. 삼각형의 (i,j) 는 삼각형 (i-1,j-1), (i-1,j) 중 큰 값에 (i,j) 를 더한 값이 최대 경로이고 그 값으로 업데이트 한다.
  4. 업데이트 된 1층 값 중 max 값을 계산한다.
fun main() {
    val br = BufferedReader(InputStreamReader(System.`in`))
    val n = br.readLine().toInt()

    // 삼각형을 입력 받는 배열 생성
    val triangle = Array(n + 1) { IntArray(n + 1) { 0 } }

    // input 을 triangle 에 집어 넣는다
    for (i in 1..n) {
        val input = br.readLine().split(" ").map { it.toInt() }
        for (j in 1..i) {
            triangle[i][j] = input[j - 1]
        }
    }

    // triangle (i,j) 를 위에 칸 혹은 왼쪽 위에칸 중 더 큰 값과 합해서 대입한다
    for (i in 1..n) {
        for (j in 1..i) {
            triangle[i][j] = triangle[i][j] + max(triangle[i - 1][j - 1], triangle[i - 1][j])
        }
    }

    // 마지막 줄의 값 중에 가장 큰 값을 출력
    println(triangle[n].max())
}

📚 새롭게 알게된 내용

DP 를 오랜만에 풀어보니깐 새록새록하네요. 다음엔 좀 더 어려운 DP 도 도전해보겠습니다.

@Munbin-Lee Munbin-Lee closed this Feb 11, 2024
@alstjr7437 alstjr7437 deleted the test branch February 20, 2024 05:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants