Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 319C Kalila and Dimna - Walkthrough

Tracing the full solution

Reach tower nn with minimum cost. From tower ii, jump to any j>ij > i with cost depending on heights. Rewrite: dp[j]=mini<j(dp[i]+biaj)dp[j] = \min_{i < j}(dp[i] + b_i \cdot a_j).

This is min(mix+ci)\min(m_i \cdot x + c_i) where mi=bim_i = b_i, ci=dp[i]c_i = dp[i], x=ajx = a_j. Lines have slopes bib_i. If slopes are sorted, use deque. Otherwise, use Li Chao tree or sort offline. Query aja_j on the hull to get dp[j]dp[j]. Add line (bj,dp[j])(b_j, dp[j]) for future queries. Total: O(n)O(n) or O(nlogn)O(n \log n).