{"id":280,"date":"2026-11-13T12:36:48","date_gmt":"2026-11-13T04:36:48","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-the-hungarian-algorithm-solves-an-assignment\/"},"modified":"2026-11-13T21:58:25","modified_gmt":"2026-11-13T13:58:25","slug":"how-the-hungarian-algorithm-solves-an-assignment","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-the-hungarian-algorithm-solves-an-assignment\/","title":{"rendered":"How the Hungarian algorithm solves an assignment"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> The <strong>Hungarian algorithm<\/strong>, or Kuhn-Munkres, solves the assignment problem: pair n agents with n jobs so that the sum of costs is minimum. It maintains dual variables on agents and jobs so that a reduced cost c(i, j) \u2212 u(i) \u2212 v(j) is never negative, and it grows an alternating tree in the equality subgraph where the reduced cost is zero. A phase ends by augmenting the matching or by raising duals. The time is <strong>O(n\u00b3)<\/strong> for a dense n by n cost matrix.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Minimum-cost bipartite matching with equal sides is the assignment problem. Cardinality algorithms ignore the costs. Min-cost flow solves the problem and hides the combinatorics inside a flow code. The Hungarian algorithm keeps the duals explicit. Complementary slackness says a perfect matching of tight edges, those with reduced cost zero, is optimal. The algorithm grows such a matching and changes the duals when the tight graph has no augmenting path.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A phase starts at a free agent and builds an alternating tree of tight edges. If the tree reaches a free job, the matching augments. If it stalls, every job in the tree is matched and a dual update creates a new tight edge out of the tree, or makes an existing one tight, without destroying tightness inside.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The algorithm returns a perfect matching of minimum total cost, or reports that none exists if some costs are forbidden. For a full matrix it always exists. Time is O(n\u00b3) with the classical dense implementation that scans the matrix to find the dual step. Extra memory is the dual arrays, the mate array, and the tree. The same optimum is what successive shortest paths compute on the assignment flow network.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Maximizing a weight matrix is minimizing the negated weights, after a shift that keeps the implementation&#8217;s nonnegativity if it assumes nonnegative reduced costs. The dual update&#8217;s step size is the minimum reduced cost on an edge from the tree&#8217;s agents to a job outside the tree. A wrong step goes negative and the invariant dies, or stays zero and the phase loops.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Subtract the minimum of each row from that row, then the minimum of each column from that column, or initialize duals u and v so that every reduced cost is nonnegative. Start with an empty matching.<\/li>\n<li>While some agent is free, grow an alternating tree of tight edges from that agent.<\/li>\n<li>If the tree reaches a free job, augment the matching along the tree path and start the next free agent.<\/li>\n<li>If the tree stalls, let \u03b4 be the smallest reduced cost from an agent in the tree to a job outside it. Add \u03b4 to u on tree agents and subtract \u03b4 from v on tree jobs. New tight edges appear. Continue the tree.<\/li>\n<li>When every agent is matched, the matching is optimal and its cost equals the sum of all duals.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The cubic bound is for a dense n by n assignment. A sparse min-cost matching with supplies and demands is min-cost flow. Cardinality without costs is Hopcroft-Karp or Kuhn. The dual step has to be the minimum reduced cost. A fixed step of 1 is correct only for integer costs and can be slow, and it is wrong for general reals if it overshoots.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the dual step overshoots the next tight edge<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Raise duals by 1 on integer data with large costs<\/td>\n<td>The matching stays correct if the step never skips a tight edge, and the number of raises can become proportional to the cost values. The minimum reduced cost finishes a phase in polynomial matrix scans.<\/td>\n<\/tr>\n<tr>\n<td>Augment along a non-tight edge<\/td>\n<td>Complementary slackness fails. The matching can be perfect and still more expensive than the duals claim.<\/td>\n<\/tr>\n<tr>\n<td>Use Kuhn&#8217;s algorithm and then sort by cost<\/td>\n<td>Cardinality matching does not look at costs. A cheap edge it ignored can be part of the unique optimum.<\/td>\n<\/tr>\n<tr>\n<td>Forget the column dual when reading the cost<\/td>\n<td>The reduced cost is c(i, j) \u2212 u(i) \u2212 v(j). Dropping v makes a tight edge look positive and stalls a phase that should augment.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Unweighted bipartite matching belongs to Hopcroft-Karp. A general min-cost flow, with capacities above one, belongs to successive shortest paths or a cost-scaling push-relabel. The Hungarian algorithm is the assignment special case with the duals in the open.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment grows an alternating tree on tight edges and raises duals by the smallest reduced cost when the tree stalls. The assignment cost equals the brute-force minimum, <code>5<\/code>.<\/p>\n\n<pre><code class=\"language-python\">import itertools\ncost = [[4, 1, 3], [2, 0, 5], [3, 2, 2]]\n\ndef hungarian(a):\n    n = len(a)\n    u = [0] * (n + 1)\n    v = [0] * (n + 1)\n    p = [0] * (n + 1)\n    way = [0] * (n + 1)\n    for i in range(1, n + 1):\n        p[0] = i\n        j0 = 0\n        minv = [10 ** 9] * (n + 1)\n        used = [False] * (n + 1)\n        while True:\n            used[j0] = True\n            i0 = p[j0]\n            delta, j1 = 10 ** 9, 0\n            for j in range(1, n + 1):\n                if used[j]:\n                    continue\n                cur = a[i0 - 1][j - 1] - u[i0] - v[j]\n                if cur &lt; minv[j]:\n                    minv[j] = cur\n                    way[j] = j0\n                if minv[j] &lt; delta:\n                    delta, j1 = minv[j], j\n            for j in range(n + 1):\n                if used[j]:\n                    u[p[j]] += delta\n                    v[j] -= delta\n                else:\n                    minv[j] -= delta\n            j0 = j1\n            if p[j0] == 0:\n                break\n        while True:\n            j1 = way[j0]\n            p[j0] = p[j1]\n            j0 = j1\n            if j0 == 0:\n                break\n    assign = [p.index(i) - 1 for i in range(1, n + 1)]\n    return sum(a[i][assign[i]] for i in range(n))\n\nbrute = min(sum(cost[i][perm[i]] for i in range(3)) for perm in itertools.permutations(range(3)))\nassert hungarian(cost) == brute == 5\nprint(hungarian(cost))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Hungarian algorithm, Kuhn-Munkres, solves an assignment with costs. <strong>SciPy<\/strong> <code>linear_sum_assignment<\/code> is that solver, and multi-object tracking uses it to match detections to tracks. An unweighted matching uses Hopcroft-Karp and ignores cost.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop a hand-rolled Hungarian implementation if a tested min-cost flow solver is already the tool and the matrix is only one client. Keep the algorithm when the problem is an n by n assignment and the O(n\u00b3) dual growth is the intended solution.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for the Hungarian algorithm returns the tight-edge tree and the dual step equal to the minimum reduced cost leaving the tree. <strong>The Hungarian algorithm solves the n by n assignment problem in O(n\u00b3) time by growing a matching of tight edges and raising duals when that growth stalls.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: The Hungarian algorithm, or Kuhn-Munkres, solves the assignment problem: pair n agents with n jobs so that the sum of costs is minimum. It maintains dual variables on agents and jobs so that a reduced cost c(i, j) \u2212 u(i) \u2212 v(j) is never negative, and it&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,32],"tags":[],"class_list":["post-280","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-graphs"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=280"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/280\/revisions"}],"predecessor-version":[{"id":679,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/280\/revisions\/679"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=280"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=280"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}