3.7.15 · D3 · HinglishAlgorithm Paradigms

Worked examplesBitmask DP — TSP intro

2,594 words12 min read↑ Read in English

3.7.15 · D3 · Coding › Algorithm Paradigms › Bitmask DP — TSP intro

Yeh parent TSP intro ka practice-until-it-hurts companion hai. Wahan humne state dp[SET][SPOT] aur transition build kiya tha. Yahan hum isse run karte hain — har us case ke liye jo problem throw kar sakti hai — tiny inputs, degenerate graphs, asymmetric costs, path-vs-cycle, aur ek exam trap. Agar koi scenario exam mein surprise kare, toh sirf isliye hona chahiye kyunki tum bhool gaye, na ki isliye kyunki tune kabhi dekha hi nahi.


Scenario matrix

Neeche har cell DP ke behave karne ka ek alag tarika hai. Har worked example ko woh cell(s) tag kiya gaya hai jo wo cover karta hai.

Cell Case class Kya special hai Covered by
A Sabse chhota non-trivial () Do cities, ek round trip — base case barely hilta hai Ex 1
B Symmetric triangle () Dono directions equal; har jagah ties Ex 2
C Asymmetric graph dist[i][j] ≠ dist[j][i] (one-way roads) — direction matters Ex 3
D Missing edge (∞ cost) Do cities ke beech koi road nahi; DP ko route around karna padega Ex 4
E Degenerate: unreachable state Ek dp[mask][i] jo par reh jaata hai aur skip karna padta hai Ex 4, Ex 6
F Path, cycle nahi Return edge drop karo; answer badal jaata hai Ex 5
G Real-world word problem Ek story ko dist matrix mein translate karo Ex 6
H Exam twist: "fixed start ≠ fixed end" 0 se start, ek given city par end karna zaroori Ex 7
I Limiting behaviour / sanity Numbers badhne par kya bante hain; brute-force cross-check Ex 8

Example 1 — Cell A: sabse chhota tour ()

Steps.

  1. Base: dp[01][0] = dp[1][0] = 0. Yeh step kyun? Har DP ko us akele state ko seed karke shuru kiya jaata hai jisko hum free mein jaante hain: start par baithna, sirf visit kiya hua, cost .
  2. City 1 tak pahuncho: dp[11][1] = dp[01][0] + dist[0][1] = 0 + 7 = 7. Yeh step kyun? mask=11 matlab visited; 1 par end karne ke liye hum last edge peel karte hain.
  3. Tour close karo: full = 11, answer . Yeh step kyun? TSP ek cycle hai, isliye hum return edge ka cost pay karna zaroori hai (parent mein Mistake #3).

Verify: sirf possible route hai. Minimise karne ke liye kuch nahi hai — match karta hai. ✓ (Units: cost units, consistent.)


Example 2 — Cell B: symmetric triangle, ties ()

Yeh parent ka Worked Example 1 hai, re-run kiya gaya taaki neeche ki figure dono competing final routes side by side dikhaye.

Figure — Bitmask DP — TSP intro

Steps.

  1. dp[011][1] = 0 + 10 = 10 ( jaao); dp[101][2] = 0 + 15 = 15 ( jaao). Yeh step kyun? Base state se hum har unvisited city ki taraf branch karte hain — yeh do pehle moves hain.
  2. dp[111][2] = dp[011][1] + \text{dist}[1][2] = 10 + 20 = 30. Yeh step kyun? Mask ko 2 par end karte hue fill karo, 1 se aake.
  3. dp[111][1] = dp[101][2] + \text{dist}[2][1] = 15 + 20 = 35. Yeh step kyun? Sab kuch fill karne ka doosra tarika, 1 par end karte hue, 2 se aake.
  4. Close: . Yeh step kyun? Do full-mask states, do return edges — sasta wala lo.

Verify: ; . Tie real hai (figure mein do coloured loops dekho — same edges, opposite direction). ✓


Example 3 — Cell C: asymmetric graph (one-way roads)

Steps.

  1. Pehle moves: dp[011][1] = dist[0][1] = 1; dp[101][2] = dist[0][2] = 9. Yeh step kyun? Direction ab matter karta hai — ka cost 1 hai lekin ka cost 9 hai. DP dono ko honestly record karta hai.
  2. dp[111][2] = dp[011][1] + dist[1][2] = 1 + 2 = 3.
  3. dp[111][1] = dp[101][2] + dist[2][1] = 9 + 9 = 18. Yeh steps kyun? Tour do tarike se complete karo; expensive branch (18) haar jaayega.
  4. Close: . Yeh step kyun? Return edge bhi directional hai — sasta hai (3), mehnga hai (9).

Verify: cheap loop ; other loop . DP ne 6 liya. ✓ Isliye hum dist[i][j] ko ek full matrix mein store karte hain, kabhi assume nahi karte ki dist[i][j]==dist[j][i].


Example 4 — Cells D + E: ek missing road (∞ edge → unreachable state)

Steps.

  1. dp[011][1] = 4, dp[101][2] = 6. Yeh step kyun? 0 se dono pehle hops exist karte hain, isliye dono states finite hain.
  2. dp[111][2] = dp[011][1] + \text{dist}[1][2] = 4 + \infty = \infty. Yeh step kyun? Full mask ke saath 2 par end karne ka sirf ek tarika hai se, jo exist nahi karta — yeh state unreachable hai (Cell E). Code mein, if dp[mask][i]==INF: continue ise skip karta hai.
  3. dp[111][1] = dp[101][2] + \text{dist}[2][1] = 6 + \infty = \infty. Yeh step kyun? Symmetrically dead — 1 par end karne ke liye chahiye, jo bhi missing hai.
  4. Close: . Yeh step kyun? Dono full-mask states hain, isliye answer = koi valid tour nahi.

Verify: 3 cities par koi bhi Hamiltonian cycle edge use karta hai (ek triangle mein sab teeno ko visit karke close karne ka koi doosra tarika nahi). Kyunki woh edge missing hai, koi cycle exist nahi karta. DP correctly return karta hai. ✓ Yeh Hamiltonian Path and Cycle existence question hai jo DP ke andar free mein surface ho raha hai.


Example 5 — Cell F: Hamiltonian path (ghar wapas nahi)

Steps.

  1. Example 2 ka DP table reuse karo — internal states identical hain; sirf final aggregation change hoti hai. Yeh step kyun? Recurrence ne kabhi return edge use nahi ki, isliye last line se pehle kuch bhi alag nahi hai.
  2. Path answer . Yeh step kyun? Path ke liye hum dist[i][0] add nahi karte; bas end karne ki sabse sasti jagah lete hain (Mistake #3 ne doosri direction handle ki thi).

Verify: path ; path . Sabse sasta 30 hai, aur (cycle) as forecast. ✓


Example 6 — Cells G + E: word problem (delivery driver)

Matrix banao (symmetric):

Steps. Hum chaar candidate delivery orders evaluate karte hain ( ke saath tours hain, lekin symmetry unhe 3 distinct costs mein pair karta hai — har ek ek baar count hota hai):

  1. .
  2. .
  3. . Yeh steps kyun? Har row ek full-mask endpoint choice hai jo DP compare karega; DP ka min sabse chhota pick karta hai.
  4. Answer , route depot→A→B→C→depot. Yeh step kyun? DP ki closing line exactly yahi comparison automatically karti hai.

Verify: minutes, aur yeh doosron ko beat karta hai. Units: har jagah minutes, koi mixing nahi. ✓ (Cell E note: koi bhi intermediate dp[mask][i] jahan bit i mask mein nahi tha, par raha aur skip hua — same guard jaise Ex 4.)


Example 7 — Cell H: exam twist, ek specific city par end karna zaroori

Steps.

  1. Fixed endpoint ka matlab answer exactly hai — last city par minimise nahi, aur koi return edge nahi. Yeh step kyun? "C par end karo" dono — endpoint ka free choice aur return term — remove karta hai.
  2. 3 par end hone wale orders enumerate karo, 0 se start karke:
    • .
    • . Yeh step kyun? C ko last aane ke yeh do tarike hain; DP dp[1111][3] mein sasta wala store karta hai.
  3. Answer .

Verify: . Yeh cycle (18) se sasta hai kyunki hum depot edge (cost 4) skip karte hain: . Consistent. ✓ Lesson: ek fixed end general path se bhi aasaan hai — tum ek cell padhte ho, dp[full][target].


Example 8 — Cell I: limiting behaviour & brute-force cross-check

Steps.

  1. States . Yeh step kyun? masks current-city slots — table ka size (dekho Held-Karp Algorithm).
  2. Transitions (upper bound; unreachable/illegal states ise prune karte hain). Yeh step kyun? Har state predecessors par minimise karta hai — extra factor .
  3. Brute force full tours try karta hai. Tiny ke liye brute force kam operations hai — DP ki jeet sirf badhne par dikhti hai. Yeh step kyun? par, ; exponential-vs-factorial crossover (parent ka 80/20) lagbhag par hai aur tak astronomical ho jaata hai.
  4. Cross-check: 6 tours par brute force costs deta hai → min , Example 6 se match karta hai. Yeh step kyun? Do independent methods ka agree karna sabse strong sanity check hai (Branch and Bound same optimum tak prune karta).

Verify: , , , aur brute-force min DP answer. Sab confirm. ✓


Recall Kaun si final line kis question ke liye?

Closed tour (cycle) ::: min over i!=0 of dp[full][i] + dist[i][0] Path, koi bhi endpoint ::: min over i of dp[full][i] Path, fixed endpoint t ::: bas dp[full][t] (ek cell, koi min nahi) Koi valid tour exist nahi karta ::: chosen expression evaluate karta hai


Connections

  • Bitmask DP — TSP intro (index 3.7.15) — parent (state + recurrence wahan build ki gayi)
  • Travelling Salesman Problem — woh problem jo yeh examples solve karte hain
  • Held-Karp Algorithm — is DP ka formal naam; Ex 8 mein complexity
  • Dynamic Programming — optimal-substructure backbone
  • Bit Manipulation / Subset Enumeration — masks kaise index hoti hain
  • Hamiltonian Path and Cycle — existence Ex 4 mein surface hui
  • Branch and Bound — alternative exact method (Ex 8 cross-check idea)
  • 🇮🇳 3.7.15 Bitmask DP — TSP intro (Hinglish)