[TIL] Algorithms Day 10 - DP

03/16/23

·

1 min read

[TIL] Algorithms Day 10 - DP

Problem 1. GCD and LCM

import math

a, b = map(int, input().split())

gcd = math.gcd(a, b)
print(gcd)
print(a * b // gcd)

Problem 2. Triangle Permutation

tri = [0 for i in range(101)]
tri[1] = 1
tri[2] = 1
tri[3] = 1

for i in range(4, 101):
    tri[i] = tri[i-3] + tri[i-2]

T = int(input())

for _ in range(T):
    N = int(input())
    print(tri[N])

Problem 3. RGB Distance

N = int(input())
costs = []

for _ in range(N):
    costs.append(list(map(int, input().split())))

for i in range(1, N):
    costs[i][0] = min(costs[i-1][1], costs[i-1][2]) + costs[i][0]
    costs[i][1] = min(costs[i-1][0], costs[i-1][2]) + costs[i][1]
    costs[i][2] = min(costs[i-1][0], costs[i-1][1]) + costs[i][2]

print(min(costs[N-1]))

Problem 4. Integer Triangle

n = int(input())
tri = []
for i in range(n):
    tri.append(list(map(int, input().split())))

for i in range(1, n):
    for j in range(len(tri[i])):
        if j == 0:
            tri[i][j] += tri[i-1][j]
        elif j == i:
            tri[i][j] += tri[i-1][j-1]
        else:
            tri[i][j] += max(tri[i-1][j-1], tri[i-1][j])

print(max(tri[n-1]))