Exercises — Bitmask DP — TSP intro
3.7.15 · D4· Coding › Algorithm Paradigms › Bitmask DP — TSP intro
Poore note mein, cities number hain, tour city 0 se start aur end hota hai, aur edge ka cost hai. DP table hai = city se cheapest path jo exactly set mask visit kar chuka hai aur abhi city pe khada hai.
Level 1 — Recognition
Exercise L1.1 — Read a mask
n = 5. Mask integer hai. Kaun si cities visit hui hain, aur kitni? Binary likho.
Recall Solution
A mask is just an integer whose binary digits are tick-boxes. Bit set hai ⟺ city visit hui.
. 5 bits mein binary (bit4…bit0): 10110.
Right-to-left padhte hain: bit0=0, bit1=1, bit2=1, bit3=0, bit4=1.
Visit ki gayi cities: — teen cities.
Exercise L1.2 — Bit tests
mask = 22 ke saath (upar jaisa), har expression evaluate karo aur batao iska matlab kya hai:
(a) mask & (1<<2) (b) mask & (1<<3) (c) mask | (1<<0) (d) mask & ~(1<<1).
Recall Solution
Yaad karo 1<<i = "woh integer jisme sirf bit on hai".
(a) 1<<2 = 4; 22 & 4 = 4 (non-zero) → city 2 visit HUI hai.
(b) 1<<3 = 8; 22 & 8 = 0 → city 3 visit NAHI hui.
(c) 1<<0 = 1; 22 | 1 = 23 → city 0 add karo, giving .
(d) ~(1<<1) bit1 clear karta hai; 22 & ~2 = 20 → city 1 remove karo, giving .
Exercise L1.3 — Total states
General ke liye, table mein kitni entries hain, aur kitni reachable hain (matlab bit , mask mein set ho)? ke liye count do.
Recall Solution
Masks range karte hain, to masks; current city ke choices hain → table slots.
Ek slot meaningful tabhi hota hai jab bit , mask mein set ho (tum kisi unvisited city pe "end" nahi kar sakte). Fixed ke liye, exactly aadhe masks mein bit on hota hai: . Saare ke upar: reachable slots.
ke liye: table slots, reachable .
Level 2 — Application
Exercise L2.1 — Base case
ke liye full initial dp table likho (sirf non- entry list karo) aur batao kyun har doosri entry hai.
Recall Solution
dp[1][0] = 0 — yani dp[001][0]: sirf city 0 visit hui, 0 pe khade hain, cost 0.
Baaki sab hai kyunki start mein koi aisa path nahi jisne pehle se doosri cities visit ki hon. Entry ka matlab literally hai "yeh situation abhi reachable nahi." Jaise DP aage badhti hai yeh fill hote jaate hain.
Exercise L2.2 — Run 3 cities by hand
Distances (symmetric): .
Full closed-tour TSP cost compute karo. Har dp entry dikhao.
Recall Solution
Base: dp[001][0]=0.
Peel-the-last-edge transition: , mask & ~(1<<i).
| State | Compute | Value |
|---|---|---|
dp[011][1] |
dp[001][0]+dist[0][1]=0+5 |
5 |
dp[101][2] |
dp[001][0]+dist[0][2]=0+9 |
9 |
dp[111][2] |
dp[011][1]+dist[1][2]=5+4 |
9 |
dp[111][1] |
dp[101][2]+dist[2][1]=9+4 |
13 |
Cycle close karo (return edge to 0 add karo): Dono orders aur ka cost hai. Answer: 18. ✓
Exercise L2.3 — Reading a transition
, dp[mask][2] compute kar rahe hain with mask = 0111 . prev, valid predecessors , aur full expression list karo.
Recall Solution
Check karo endpoint legal hai: 0111 ka bit2 1 hai ✓ (city 2 visit hui hai).
prev = 7 & ~(1<<2) = 0111 & 1011 = 0011 .
Valid predecessors woh cities hain jo prev mein hain: .
City 3 prev mein nahi hai (bit3 = 0), to yeh candidate nahi — tum kisi aisi city se nahi aa sakte jo tumne kabhi visit hi nahi ki.
Level 3 — Analysis
Exercise L3.1 — Why not store the order?
Ek dost insist karta hai: "Do tours jinhone visit kiya aur 2 pe end hue, lekin alag orders mein ( vs ... ruko, woh 1 pe end hota hai) — surely order future badal deta hai." Precisely rebut karo: kyun hum same-(set, spot) states ko collapse kar sakte hain?
Recall Solution
Remaining cost — tour finish karne ka cost — depend karta hai sirf (a) kaun si cities abhi visit karni hain (= mask ka complement) aur (b) tum abhi kahan khade ho (city ). Dono mein capture hain. Already-visited prefix ka internal order sirf prefix ke apne accumulated cost ko affect karta hai, jo pehle se value ke roop mein stored hai.
To do paths jo same reach karte hain woh aage se interchangeable hain; hum cheaper value rakhte hain aur doosri discard karte hain. Yahi memorylessness hai jo state ko chhota rakhti hai: orderings ki jagah states. Neeche figure dekho.

Exercise L3.2 — Count the work
ke liye compute karo (i) states ki sankhya, (ii) roughly total transitions , aur (iii) se compare karo. Ratio ka order-of-magnitude batao.
Recall Solution
(i) States . (ii) Transitions (lagbhag ) — computer ke liye trivial. (iii) . Ratio . Bitmask DP yahaan lagbhag 4500× kam kaam karta hai — aur badhne ke saath gap explosively badhta hai.
Exercise L3.3 — Where does optimal substructure come from?
Ek clean argument mein batao, kyun jo min ke andar appear hota hai, khud optimal hona chahiye (exchange argument).
Recall Solution
Maan lo ka best path edge pe end hota hai, aur uska prefix ( tak ka path) ka cost tha. Agar tak koi sasta path hota cost ke saath, to hum edge usse jod sakte the aur tak cost wala path paate — supposed best ko beat karte hue. Contradiction. Isliye prefix already optimal hona chahiye, yani ke barabar. Yeh "cut-and-paste" exactly woh optimal-substructure property hai jo recurrence ko legal banati hai.
Level 4 — Synthesis
Exercise L4.1 — Hamiltonian path, not cycle
L2.2 ke same distances ke saath (), cheapest Hamiltonian path dhundho (0 se start, sab visit karo, return nahi). Kaun sa endpoint jeetta hai?
Recall Solution
Return term drop karo; answer sab ke upar (including ? nahi — city 0 fixed start hai, to yahaan kyunki path sab visit karne ke baad kahin aur end hona chahiye).
L2.2 se: dp[111][1]=13, dp[111][2]=9.
, city 2 pe end hokar route se milta hai.
Yeh cycle (18) se sasta hai precisely kyunki humne expensive return edge skip ki. Yeh Hamiltonian Path and Cycle distinction action mein hai.
Exercise L4.2 — Fixed start AND fixed end (path)
Ab require karo ki path 0 se start ho aur city 1 pe end ho, sab visit karte hue, same distances. Cost?
Recall Solution
Hum directly chahte hain — endpoints par min nahi, kyunki endpoint 1 par pinned hai.
full = 111. L2.2 se, dp[111][1] = 13 (route : ).
1 pe end hone ka aur sirf ek hi tarika hai sab visit karke; aur ek hi "middle" city hai 2, to forced hai. Answer: 13.
Lesson: endpoint pin karna matlab hai ek single table cell padhna, minimize karna nahi.
Exercise L4.3 — Asymmetric distances (one-way roads)
, lekin ab directed: . 0 se start/end hote hue cheapest closed tour dhundho. Dikhao ki dono directions alag hain.
Recall Solution
Yahaan dist[j][i] ≠ dist[i][j], to direction matter karta hai — isliye transition dist[j][i] use karta hai dist[i][j] nahi.
| State | Compute | Value |
|---|---|---|
dp[011][1] |
dp[001][0]+d[0][1]=0+2 |
2 |
dp[101][2] |
dp[001][0]+d[0][2]=0+6 |
6 |
dp[111][2] |
dp[011][1]+d[1][2]=2+1 |
3 |
dp[111][1] |
dp[101][2]+d[2][1]=6+9 |
15 |
Close karo: .
Winning tour ka cost hai. Reverse . Directions bahut alag hain — answer 6, aur sirf DP ka directional dist[j][i] isse pakadta hai.
Level 5 — Mastery
Exercise L5.1 — Multiple start cities (metric closure trick)
Tum tour kisi bhi city se start kar sakte ho (phir bhi ek closed cycle jo sab visit kare). Kya start ko 0 fix karne se optimality lose hoti hai? Apna answer prove karo.
Recall Solution
Koi optimality lose nahi hoti. Ek closed tour ek cycle hai; ek cycle ka koi distinguished starting point nahi hota — woh same edges visit karta hai chahe tum kaunsa vertex "start" kaho. To optimal cycle city 0 se guzarta hai, aur traversal city 0 se shuru karne ke liye apna labelling rotate karna usi cycle ko same cost ke saath describe karta hai. Isliye start fix karna phir bhi global optimum dhundh leta hai. (Caveat: yeh cycle version ke liye valid hai. Free start wali path ke liye, tum base case ko saare start cities par loop karte, kaam se multiply hota.)
Exercise L5.2 — Count optimal tours
L2.2 ke symmetric triangle () ke liye, kitne distinct closed tours optimum achieve karte hain, aur kyun? Generalise karo: symmetric instance mein exactly 2 optimal tours kab hote hain vs 1?
Recall Solution
ke liye city 0 se exactly 2 directed closed tours hain: aur . Symmetric distances ke saath dono same teen edges opposite directions mein traverse karte hain, to dono hamesha same cost karte hain. Yahaan woh hai, dono tours se achieve hota hai. Generalisation: symmetric ke liye, do tours mirror images hain aur hamesha tie karte hain — hamesha exactly 2 optimal directed tours hote hain (ya tum unhe 1 undirected tour count kar sakte ho). Strict single winner tabhi aata hai jab distances asymmetric hain, mirror symmetry todti hain (jaise L4.3 mein, jahan ).
Exercise L5.3 — Memory halving via forward push
Reference implementation forward push karta hai (mask → nm = mask | (1<<k)). Argue karo kyun masks ko increasing order mein iterate karna correctness guarantee karta hai, aur woh largest do jiske liye int-indexed dp array of longs MB mein fit hota hai (assume 8 bytes/entry).
Recall Solution
Increasing order ki correctness: forward push dp[nm][k] ko dp[mask][i] se update karta hai jahan nm = mask | (1<<k) aur bit , mask mein nahi tha. Pehle-se-zero bit set karna nm > mask strictly banata hai. To increasing loop mein jab bhi hum nm reach karte hain, saare masks (har possible source including) already final hain. Koi state apne final hone se pehle read nahi hoti. ✓
Memory bound: entries , har ek 8 bytes. Chahiye bytes, yani .
- : ✓
- : ✗ Largest = 20. (Yahi Held-Karp Algorithm ki classic "" ceiling hai; iske aage tum Branch and Bound ya heuristics use karte ho.)
Recall One-line self-check summary
Mask padhna ::: integer ko powers of two mein decompose karo.
Endpoint legality ::: dp[mask][i] valid tabhi jab mask & (1<<i) ho.
Peeled edge direction ::: hamesha dist[j][i] (current city mein jaata hai).
Cycle vs path ::: cycle +dist[i][0] add karta hai; path nahi.
Free vs pinned endpoint ::: free → min_i dp[full][i]; pinned → ek cell.
Iteration order ::: increasing masks kaam karte hain kyunki bit set karna sirf mask badhata hai.
Connections
- Travelling Salesman Problem, Held-Karp Algorithm — exact problem aur algorithm jo yeh drills implement karti hain.
- Bit Manipulation, Subset Enumeration — mask machinery (L1).
- Dynamic Programming — optimal substructure (L3.3).
- Hamiltonian Path and Cycle — path vs cycle distinction (L4).
- Branch and Bound — se aage jaane ke liye kya use karte hain (L5.3).