Sei sulla pagina 1di 12

03.

Latihan Soal DP
Coin-row problem
• There is a row of n coins whose values are some positive integers c1,
c2, . . . , cn, not necessarily distinct. The goal is to pick up the
maximum amount of money subject to the constraint that no two
coins adjacent in the initial row can be picked up.
• Example:
• Coin = [5, 1, 2, 10, 6, 2]  ans = 17
• Coin = [5, 1, 2, 10, 6]  ans = 15
1. Perhitungan Manual
2. Recurrence  overlapping sub-problem
• 𝐹 𝑛 = max 𝐶 𝑛 + 𝐹 𝑛 − 2 , 𝐹 𝑛 − 1
• Base case:
• F[0] = 0
• F[1] = C[1]
• Recursive case:
• max 𝐶 𝑛 + 𝐹 𝑛 − 2 , 𝐹 𝑛 − 1
3. Pseudocode Recursive (1)
// total == len + 1
Coin-Row-Rec(R, len)
1. if (len == 0)
2. return 0
3. if len == 0
4. return R[1]
5. else
6. R[len] = max(R[len] + Coin-Row-Rec(R, len-2), Coin-Row-Rec(R,
len-1))
7. if (len == total)
8. return R[len]
9. else
10. return 0
3. Pseudocode Recursive (2)
CoinRow(i, P)
1. nilai = -9999
2. for i to 6
3. nilai = max(nilai, P[i] + CoinRow(i+2, P)
4. return nilai

1. Base case belum ada


2. Jumlah koin hanya diasumsikan sebanyak 6, padahal
seharusnya sebanyak n
3. Pseudocode Recursive (3)
Coin-Row(C, n) Base case:
1. if n == 0 F[0] = 0
2. return 0 F[1] = C[1]
Recursive case:
3. if n == 1 max 𝐶 𝑛 + 𝐹 𝑛 − 2 , 𝐹 𝑛 − 1
4. return C[1]
5. ans = -INF
6. ans = max(C[n] + CoinRow(C, n-2), CoinRow(C, n-1))
7. return ans
4. Pseudocode DP-Top Down
• Tambahkan memo di dalam algoritma DP yang dipilih
// F = memo untuk menyimpan hasil
Coin-Row(C, n)
1. if F[n] > 0
2. return F[n]
3. if n == 0
4. F[0] = 0
5. return F[0]
6. if n == 1
7. F[1] = C[1]
8. return F[1]
9. else
10. F[n] = max(C[n] + CoinRow(C, n-2), CoinRow(C, n-1))
11. return F[n]
4. Pseudocode DP-Top Down
• Tambahkan memo di dalam algoritma DP yang dipilih
// F = memo untuk menyimpan hasil
Coin-Row(C, n)
1. if F[n] > 0
2. return F[n]
3. if n == 0
4. F[n] = 0
5. if n == 1
6. F[n] = C[1]
7. else
8. F[n] = max(C[n] + CoinRow(C, n-2), CoinRow(C, n-1))
9. return F[n]
5. Pseudocode DP-Bottom Up  loop biasa +
memo
• Lihat pada buku Introduction to Design and Analysis Algorithm
(Levitin) halaman 287

// F = memo untuk menyimpan hasil


Coin-Row(C, n)
1. F[0] = 0
2. F[1] = C[1]
3. for i = 2 to n
4. F[n] = max(C[n] + F[n-2], F[n-1])
5. return F[n]
6. Menentukan sub-solusi yang terpilih (a)
// F = memo untuk menyimpan hasil
// S = solusi koin yang terpilih  diinisialisasi isinya 0 semua
• Coin-Row(C, n)
1. if F[n] > 0
2. return F[n]
3. if n == 0
4. F[n] = 0
5. if n == 1
6. F[n] = C[1]
7. else
8. left = C[n] + CoinRow(C, n-2)
9. right = CoinRow(C, n-1)
10. if (left > right)
11. S[n] = 1
12. S[n-2] = 1
13. else
14. S[n-1] = 1
15. F[n] = max(left, right)
16. return F[n]
6. Menentukan sub-solusi yang terpilih (b)
Print-Selected-Coin(S)
1. for i = 1 to n
2. if S[i] == 1
3. print C[i] + “ ”

Potrebbero piacerti anche