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

21-SeongHoonC #77

Merged
merged 7 commits into from
Apr 17, 2024
Merged

21-SeongHoonC #77

merged 7 commits into from
Apr 17, 2024

Conversation

SeongHoonC
Copy link
Collaborator

@SeongHoonC SeongHoonC commented Apr 11, 2024

🔗 문제 링크

RGB거리

✔️ 소요된 시간

30분

✨ 수도 코드

풀이를 GIF 로 만들어봤습니다.!!

RGB거리움직임

집 2 지붕을 빨간색 하는 최소 비용은 "집 1 초록색 선택", "집 1 파란색 선택" 중 최소값에 집 2 빨갠색 비용을 더하면 된다.
image

그럼 집 2까지 지붕을 칠하는 최소 비용은 다음과 같다.

image

마지막 집까지 하고 최소값을 구하면..! 답은 96 이 나온다.

image
// 비용 최대값
private const val MAX = 987_654_321 
// 색깔 범위 R(1), G(2), B(3)
val colors = 1..3

fun main() {
    val br = BufferedReader(InputStreamReader(System.`in`))
    val n = br.readLine().toInt()

    // 각 집마다 비용 입력받기
    val graph = Array(4) { Array(n + 1) { 0 } }

    for (i in 0 until n) {
        val line = br.readLine().split(" ").map { it.toInt() }
        for (j in 0..2) {
            graph[j + 1][i + 1] = line[j]
        }
    }

    // 각 집까지 최소 비용
    val dp = Array(4) { Array(n + 1) { 0 } }

    // 각 집마다 현재 이 색을 칠할 때 최소값을 구한다
    for (houseIndex in 1..n) {
        for (colorIndex in colors) {
            dp[colorIndex][houseIndex] = colors.minOf {
                if (it == colorIndex) MAX else dp[it][houseIndex - 1] + graph[colorIndex][houseIndex]
            }
        }
    }
    println(colors.minOf { dp[it][n] })
}

📚 새롭게 알게된 내용

DP 는 깃헙 브랜치, 평행세계와 비슷하게 풀어야되는 것 같다~
keynote 를 사용하면 gif 만들기가 쉽게 가능하다!

@alstjr7437
Copy link
Member

코테 느낌나려고 문제 유형을 보지 않고 풀었는데..


저는 제일 작은 부분이 있으면 그 부분 다음 부분을 1000으로 못들어가게 해줬었는데
26 40 83
49 60 57
13 89 99

26 40 83 -> 26 idx 1
1000 60 57 -> 57 idx 2
13 89 1000 -> 13 idx 1

으로 했지만 마지막 예제에서 막혀서 다시 생각하니

5 10 10 -> 5 idx 1
1 300 300 -> 300 idx 2
3 10 10 -> 3 idx 1

308이 되지만

원래의 답은 10 + 1 + 10 = 21이 되야하는데 만족을 못했습니다.


그래서 문제 유형을 보고 나니까 각 자리를 계속해서 누적해서 마지막까지 가면 되겠구나 생각했습니다!!(성훈님과 똑같이)

let n : Int = Int(readLine()!)!
var homes : [[Int]] = Array(repeating: [], count: n+1)

for i in 0..<n {
    let temp : [Int] = (readLine()?.split(separator: " ").map{ Int($0)! })!
    homes[i] = [temp[0], temp[1], temp[2]]
}


for i in 1..<n {
    homes[i][0] = min(homes[i-1][1], homes[i-1][2]) + homes[i][0]
    homes[i][1] = min(homes[i-1][0], homes[i-1][2]) + homes[i][1]
    homes[i][2] = min(homes[i-1][0], homes[i-1][1]) + homes[i][2]
}

print(homes[n-1].min()!)

Copy link

@9kyo-hwang 9kyo-hwang left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 문제는 DP이긴 한데, 굳이 각 단계 별 값을 모두 저장할 필요는 없다는 게 재밌죠.
직전 단계 r, g, b 값만 기억하면 됩니다 :)

input = open(0).readline

N = int(input())

R, G, B = map(int, input().split())
for _ in range(N - 1):
    r, g, b = map(int, input().split())
    t1, t2, t3 = min(G, B) + r, min(R, B) + g, min(R, G) + b
    R, G, B = t1, t2, t3
    
print(min(R, G, B))

Copy link
Member

@fnzksxl fnzksxl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

풀고나서 교황님 코드도 보니까 확실히 그 전 값만 기억하고 있어도 충분하네요.
짬이 다르시긴 합니다. 저도 일반적인 DP로 풀어버렸습니다!

import sys

input = sys.stdin.readline

N = int(input())
DP = [0] * N

for i in range(N):
    DP[i] = list(map(int,input().split()))
    
for i in range(1,N):
    DP[i][0]= min(DP[i-1][1],DP[i-1][2]) + DP[i][0]
    DP[i][1]= min(DP[i-1][0],DP[i-1][2]) + DP[i][1]
    DP[i][2]= min(DP[i-1][0],DP[i-1][1]) + DP[i][2]

print(min(DP[N-1][0],DP[N-1][1],DP[N-1][2]))

@SeongHoonC SeongHoonC merged commit 0322b50 into main Apr 17, 2024
11 checks passed
@SeongHoonC SeongHoonC deleted the 21-SeongHoonC branch April 17, 2024 05:17
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.

4 participants