3.5.17 · Coding › Graphs
Intuition Ek-sentence ka picture
Ek graph bipartite hota hai agar uske vertices ko two groups mein split kar sako jisme har edge groups ke beech jaaye, kabhi ek group ke andar nahi . Dusre words mein: vertices ko 2 colors se paint karo taki koi bhi edge same-colored endpoints na rakh sake. Iske peechhe ka deep theorem: ek graph bipartite hai ⟺ usmein koi odd-length cycle nahi hai.
Definition Bipartite graph
Ek graph G = ( V , E ) bipartite hota hai agar V ko sets L aur R mein partition kiya ja sake (L ∪ R = V , L ∩ R = ∅ ) jisse har edge ( u , v ) ∈ E ka ==ek endpoint L mein aur ek R mein== ho. Koi bhi edge puri tarah L ke andar ya R ke andar nahi hoti.
WHY care karte hain? Bahut saare real problems "do tarah ki cheezein ek saath match" hoti hain: jobs↔workers, students↔projects, left pixels↔right pixels. Bipartiteness woh structural property hai jo matching ko efficiently solve karne laayak banati hai.
Intuition WHY "no odd cycle"?
Ek cycle ke saath alternate colors se chalo: B, W, B, W, … Start par consistent color ke saath wapas aane ke liye, cycle ki length even honi chahiye. Ek odd cycle start vertex ko dono colors dene par majboor karti hai — jo impossible hai. Isliye odd cycle = not 2-colorable = not bipartite.
Intuition Algorithm kaise sochta hai
Ek start vertex lo, usse color 0 do. Har neighbor ko force karo opposite color pe. Propagate karte raho (BFS ya DFS). Agar kabhi ek vertex ko color karne ki koshish karo aur usse already wahi color mila ho jo usse push karne wale neighbor ka hai — contradiction → odd cycle → not bipartite.
First principles se derivation. Coloring ek constraint system hai: har edge demand karti hai c u = c v over { 0 , 1 } . Sirf 2 colors ke saath, " = " ka matlab hai c v = 1 − c u — ek deterministic rule jab ek vertex fix ho jaaye. Toh ek connected component ke andar sirf do valid colorings hoti hain (saare colors swap karo), jo start se determine hoti hain. BFS/DFS bas yahi forced rule apply karta hai; clash ka matlab hai koi assignment exist nahi karta.
function isBipartite(G):
color = array of -1 for all vertices # -1 = uncolored
for each vertex s with color[s] == -1: # handle disconnected graph
color[s] = 0
queue = [s]
while queue not empty:
u = queue.pop()
for v in neighbors(u):
if color[v] == -1:
color[v] = 1 - color[u] # WHY: force opposite
queue.push(v)
elif color[v] == color[u]:
return false # WHY: same color on an edge = odd cycle
return true
1 − 2 − 3 − 4 − 1 par trace
color[1]=0. Why? Arbitrary start.
1 ke neighbors: {2,4} → color 1. Why? Forced opposite.
2 se, neighbor 3 → color 0. 4 se, neighbor 3 already 0 = 1 − color [ 4 ] , consistent. Why no clash? Cycle length 4 even hai.
✅ Bipartite: L = { 1 , 3 } , R = { 2 , 4 } .
1 − 2 − 3 − 1 par trace
color[1]=0 → color[2]=1 → color[3]=0 (2 se). Ab edge (3,1): dono 0 → clash .
Why? Triangle = length 3 ka odd cycle. ❌ Not bipartite.
Complexity: har vertex/edge ek baar touch hota hai → O ( V + E ) .
Ek matching M ⊆ E edges ka ek set hai jisme koi shared endpoints nahi hote . Ek maximum matching mein zyada se zyada edges hoti hain. Bipartite graphs mein hum L ko R se match karte hain (socho: workers ko jobs assign karna, har ek ek baar use hoga).
Definition Augmenting path
Matching M diya hua ho, ek augmenting path ek aisa path hai jo unmatched vertices se start aur end karta hai aur alternate karta hai unmatched, matched, unmatched, matched, …, unmatched edges. Iska odd length hota hai, matched se ek zyada unmatched edge ke saath.
Intuition WHY augmenting paths matching badhate hain
Path par har edge flip karo: matched↔unmatched. Matched edges (k the) free ho jaate hain; unmatched edges (k + 1 hain) matched ho jaate hain. Net gain +1 . Endpoints (pehle unmatched the) ab matched ho jaate hain, aur interior matched-ness preserve rehti hai.
Berge's theorem: M maximum hai ⟺ koi augmenting path nahi hai. (Agar ek exist karta hai to hamesha +1 kar sakte ho, isliye tum maximum nahi the.)
Bar bar free left vertex se DFS karo ek augmenting path dhundne ke liye; augment karo. O ( V ⋅ E ) .
Ek round mein ek augmenting path dhundne ki jagah, ek maximal set of shortest, vertex-disjoint augmenting paths ek saath dhundo, phir sab ko augment karo. Isse shortest augmenting path length strictly increase hoti hai har phase mein, phases ki sankhya O ( V ) par cap ho jaati hai.
HOW har phase kaam karta hai:
BFS saare free left vertices se simultaneously karo, alternating edges use karke ek layered graph (distance levels) banao. Yeh shortest augmenting distance dhundta hai.
DFS in layers ke through greedily ek maximal set of vertex-disjoint shortest augmenting paths extract karo; har ek ko augment karo.
Tab tak repeat karo jab tak BFS koi free right vertex na dhunde (no augmenting path → maximum, by Berge).
HopcroftKarp(L, R, adj):
matchL = [None]*|L|; matchR = [None]*|R|
result = 0
while BFS_builds_layers(): # phase: layered graph of shortest aug paths
for u in L if matchL[u] is None:
if DFS_augment(u): # find vertex-disjoint shortest aug path
result += 1
return result
# BFS sets dist[] for free-left layer-by-layer; DFS only follows increasing layers
Worked example Tiny matching (two phases)
L = { a , b } , R = { x , y } , edges a − x , a − y , b − x . Empty matching se shuru karo.
Phase 1 BFS: free lefts a , b dist 0 par. Free rights x , y tak edges se shortest augmenting length 1 milti hai. Layered graph mein sirf yeh length-1 paths hain.
Phase 1 DFS (maximal disjoint set of length-1 paths): a → x lo → match a − x . Ab b try karo: uska sirf ek neighbor x is phase mein already use ho chuka hai, toh b ke liye koi vertex-disjoint length-1 path nahi bachti. Why stop? Ek phase ke andar hum sirf shortest, vertex-disjoint paths use karte hain. Phase 1 deta hai +1 . Current matching: { a − x } .
Phase 2 BFS: sirf free left b hai (aur free right y ). Shortest augmenting path ab length 3 ki hai (matched edge a − x se bounce karna padega): b → x (unmatched), x → a (matched edge), a → y (unmatched). Why length grew? Exactly Hopcroft–Karp guarantee: shortest augmenting length strictly increase hoti hai har phase mein.
Phase 2 DFS: b − x − a − y along augment karo: edges flip karo → ab b − x aur a − y matched, a − x freed. +1 . Matching: { b − x , a − y } .
Phase 3 BFS: koi free left vertex nahi bachta → stop. Result = 2 (perfect matching). ✅
Common mistake "Agar graph mein koi triangle nahi hai, toh woh bipartite hai."
Why it feels right: triangles sabse chhota non-bipartite cheez hoti hai. The fix: koi bhi odd cycle (length 5, 7, …) bipartiteness tod deta hai. Pentagon C 5 triangle-free hai lekin not bipartite. Test = no odd cycle, sirf no triangle nahi.
Common mistake 2-coloring mein disconnected components bhool jaana.
Why it feels right: ek BFS "graph cover" kar leta lagta hai. The fix: graph mein kai components ho sakte hain; saare uncolored vertices par loop karo aur har ek ke liye fresh BFS start karo, warna vertices mislabel/miss ho jayenge.
Common mistake Greedy matching = maximum matching.
Why it feels right: koi bhi free edge pakad lena matching fill karta lagta hai. The fix: greedy stuck ho sakta hai (ek "maximal" matching jo "maximum" nahi hoti). Matching re-route karne ke liye augmenting paths chahiye aur complete hone ka pata karne ke liye Berge's theorem.
Common mistake "Hopcroft–Karp ek phase mein saare augmenting paths dhund leta hai."
Why it feels right: speedup bahut saare paths ek saath karne se aata hai, isliye lagta hai saare paths. The fix: har phase sirf ek maximal set of shortest vertex-disjoint augmenting paths leta hai. Lambe paths (aur vertices share karne wale) baad ke phases ke liye wait karte hain, jab shortest length badh jaati hai.
Common mistake Non-bipartite graphs par Hopcroft–Karp use karna.
Why it feels right: "yeh matching hai na?" The fix: yeh bipartite layered structure par rely karta hai. General matching ke liye Blossom algorithm chahiye (odd cycles ko contract karna padta hai). Pehle hamesha 2-color-test karo.
Recall Feynman: ek 12-saal ke bacche ko explain karo
Socho ek dance jisme ladke left par khade hain, ladkiyaan right par, aur ek hand-link sirf ladka↔ladki ke beech jaati hai, kabhi ladka↔ladka nahi. Yahi ek bipartite graph hai: do teams, links sirf across. Check karne ke liye, kisi ko red paint karo, unke saare doston ko blue, unke doston ko phir red — agar do dost kabhi same color pe aa jaayein, toh "do teams" plan fail ho jaata hai (doston ka ek odd loop hai). Matching har ladke ko ek ladki ke saath pair karna hai jisse koi double-booked na ho. Clever Hopcroft–Karp trick: har round mein yeh ek saath shortest non-overlapping "swap chains" ka ek bunch pakadta hai; chains round by round lambi hoti jaati hain, toh poori pairing super fast khatam hoti hai.
"BiP = Both Painted, no Pal same-Paint." Aur algorithm speed ke liye: "Hopcroft–Karp Hops in V Kicks of E " → O ( E V ) .
Graph Coloring — bipartite = 2-colorable special case (chromatic number ≤ 2 ).
BFS / DFS — 2-coloring test aur phases ka engine.
Maximum Flow — bipartite matching max-flow mein reduce hoti hai (unit-capacity source→L→R→sink).
Berge's Theorem — augmenting-path optimality condition.
König's Theorem — matching ⟷ vertex cover ⟷ independent set duality.
Blossom Algorithm — general (non-bipartite) graphs mein matching.
Ek graph bipartite hai iff usmein koi ... nahi hai odd-length cycle.
Edge (u,v) ke liye 2-coloring propagation rule color[v] = 1 − color[u].
BFS/DFS 2-coloring bipartiteness test ki time complexity O(V + E).
Matching ki definition edges ka ek set jisme koi do vertices share nahi karte.
Augmenting path kya hota hai? do unmatched vertices ke beech ek path jo unmatched/matched edges alternate karta hai (odd length, ek extra unmatched edge).
Berge's theorem ek matching maximum hai iff usmein koi augmenting path nahi hai.
Augmenting path ke saath edges flip karne ka effect matching size exactly 1 se badhti hai.
Hopcroft–Karp core idea har phase BFS layering + DFS se shortest vertex-disjoint augmenting paths ka ek maximal set dhundta hai, phir sab augment karta hai.
Ek Hopcroft–Karp phase mein kaun se augmenting paths use hote hain? sirf SHORTEST, vertex-disjoint augmenting paths ka ek maximal set; lambe/overlapping wale baad ke phases ke liye wait karte hain.
Hopcroft–Karp ki time complexity O(E√V).
Hopcroft–Karp mein sirf O(√V) phases kyun hote hain? shortest augmenting path length har phase mein strictly increase hoti hai, isliye √V phases ke baad sirf O(√V) augmentations bache rehte hain.
König's theorem (bipartite) max matching size = min vertex cover size.
Bipartite graph mein max independent set matching ke terms mein |V| − max matching size.
2-coloring test mein saare vertices par loop kyun karna padta hai? disconnected components handle karne ke liye.
Hopcroft–Karp general graphs par kyun use nahi kar sakte? odd cycles (blossoms) bipartite layered structure tod dete hain; Blossom algorithm use karo.
Two vertex groups L and R
Force opposite color rule