DP problems — rod cutting, egg drop, DP on trees
3.7.14· Coding › Algorithm Paradigms
1. Rod Cutting
Recurrence scratch se derive karna
KIYA CHAHIYE: = length ki rod se milne wala best revenue.
RECURSIVE SOCHNE KA TARIKA: sabse left wale piece ki koi length hogi (jahan ). Hum usse kamaate hain, aur bacha hua length ka rod ek fresh, same subproblem hai.
Toh hum har first-piece length try karte hain aur best rakhte hain:
YEH KYUN SAHI HAI: rod ki har possible cutting mein koi na koi sabse left wala piece hoga. ko saare possible leftmost lengths pe loop karke, hum guaranteed hai ki har arrangement consider ki gayi. Max lena optimum deta hai — yeh hai optimal substructure: poore ka optimal solution parts ke optimal solutions contain karta hai.
def rod_cut(p, n): # p[i] = price of length i, p[0]=0
r = [0]*(n+1)
cut = [0]*(n+1) # to reconstruct
for j in range(1, n+1):
best = float('-inf')
for i in range(1, j+1):
if p[i] + r[j-i] > best:
best = p[i] + r[j-i]
cut[j] = i
r[j] = best
return r[n], cut2. Egg Drop
Recurrence derive karna
= eggs aur floors ke saath minimum worst-case drops.
TARIKA: kisi floor se egg drop karo (current range ke neeche se count karte hue). Do cases, aur humein worst mein survive karna hai:
- Egg breaks → threshold pe ya neeche hai, neeche ke floors mein. Eggs ho jaate hain. Cost: .
- Egg survives → threshold se upar hai, upar ke floors mein. Eggs rehte hain. Cost: .
Worst case = dono ka max (adversary bura outcome choose karta hai). Is drop ke liye 1 pay karte hain, phir worst case minimize karne ke liye choose karte hain:
Base cases (WHY yeh hold karte hain):
- — zero floors, kuch test nahi karna.
- — ek floor, ek drop confirm karta hai.
- — ek egg linear scan force karta hai.
def egg_drop(eggs, floors):
D = [[0]*(floors+1) for _ in range(eggs+1)]
for f in range(1, floors+1):
D[1][f] = f
for e in range(2, eggs+1):
for f in range(1, floors+1):
best = float('inf')
for x in range(1, f+1):
worst = 1 + max(D[e-1][x-1], D[e][f-x])
best = min(best, worst)
D[e][f] = best
return D[eggs][floors]3. DP on Trees
States derive karna
KIYA CHAHIYE: har node ke liye do answers kyunki parent ki choice depend karti hai ki hum include hain ya nahi.
- = ke subtree mein best weight include karte hue.
- = ke subtree mein best weight exclude karte hue.
HOW children ko combine karo:
- Agar included hai, koi bhi child included nahi ho sakta:
- Agar excluded hai, har child include ho sakta hai ya nahi — best lo:
WHY SAHI HAI: subtrees disjoint hain, isliye unke best values simply add ho jaate hain. Adjacency constraint sirf parent ko uske direct children se couple karti hai — exactly yahi do states encode karti hain.
Answer = . Time (har edge ek baar process hoti hai).
def mwis_tree(adj, w, root=0):
# adj: adjacency list, w: weights, tree rooted at `root`
f0 = [0]*len(w); f1 = [0]*len(w)
def dfs(v, parent):
f1[v] = w[v]; f0[v] = 0
for c in adj[v]:
if c != parent:
dfs(c, v)
f1[v] += f0[c]
f0[v] += max(f0[c], f1[c])
dfs(root, -1)
return max(f0[root], f1[root])
Flashcards
Rod cutting recurrence
Rod cutting time complexity
Rod cutting kis subproblem pe recurse karta hai?
Egg drop recurrence
Egg drop mein andar max kyun?
Egg drop base cases
2 eggs, 10 floors ke saath Egg drop?
Binary search egg drop ke liye optimal kyun nahi hai?
DP-on-tree MWIS states
formula
formula
DP on tree time complexity
Trees pe DP cleanly kyun kaam karta hai?
Egg drop dual recurrence (drops se floors)
Recall Feynman: ek 12 saal ke bachche ko samjhao
Rod cutting: Tumhare paas ek lamba chocolate bar hai aur pieces ki price list hai. Tum poochh rahe ho: "Agar main pehle left mein ek chhota piece todun toh best paisa kya hai?" Har possible first piece try karo, phir bache hue bar ke baare mein wahi sawaal poochho. Computer har length ka answer yaad rakhta hai taaki dobara poochha na jaaye.
Egg drop: Tumhare paas 2 special eggs hain aur tum dhundhna chahte ho ki sabse uunchi floor kaun si hai jahan se drop karo toh nahi tootega. Agar tum koi floor guess karo aur woh toot jaaye, tumhe neeche carefully test karna padega (egg gaya!). Agar survive kare, tum upar try kar sakte ho. Tum plan karte ho taaki sabse bure din bhi kam se kam drops mein floor dhoondh lo.
DP on trees: Socho ek family tree jahan har insaan ki ek value hai, lekin parent aur child dono nahi choose ho sakte (woh ladhenge!). Tum sabse chhote bachon se shuru karo, har chhoti family ke liye best nikalte ho, phir har parent ko do notes bhejte ho: "agar tum join karo toh best" aur "agar tum bahar baitho toh best." Parent notes add karta hai. Tree ka top final best deta hai.
Connections
- Dynamic Programming — optimal substructure + overlapping subproblems
- Recursion and Memoization — teeno ke top-down version
- Greedy Algorithms — contrast: greedy MWIS & egg drop mein fail hota hai
- Binary Search — egg-drop ke ko speed up karta hai aur clarify karta hai ki akela kyun fail hota hai
- Tree Traversal (DFS) — post-order tree DP ka engine hai
- Knapsack Problem — rod cutting unbounded knapsack hai jisme length=weight=price-index