You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

791 lines
24KB

  1. #!/usr/bin/env python
  2. # -*- coding: iso-8859-1 -*-
  3. # Documentation is intended to be processed by Epydoc.
  4. """
  5. Introduction
  6. ============
  7. The Munkres module provides an implementation of the Munkres algorithm
  8. (also called the Hungarian algorithm or the Kuhn-Munkres algorithm),
  9. useful for solving the Assignment Problem.
  10. Assignment Problem
  11. ==================
  12. Let *C* be an *n*\ x\ *n* matrix representing the costs of each of *n* workers
  13. to perform any of *n* jobs. The assignment problem is to assign jobs to
  14. workers in a way that minimizes the total cost. Since each worker can perform
  15. only one job and each job can be assigned to only one worker the assignments
  16. represent an independent set of the matrix *C*.
  17. One way to generate the optimal set is to create all permutations of
  18. the indexes necessary to traverse the matrix so that no row and column
  19. are used more than once. For instance, given this matrix (expressed in
  20. Python)::
  21. matrix = [[5, 9, 1],
  22. [10, 3, 2],
  23. [8, 7, 4]]
  24. You could use this code to generate the traversal indexes::
  25. def permute(a, results):
  26. if len(a) == 1:
  27. results.insert(len(results), a)
  28. else:
  29. for i in range(0, len(a)):
  30. element = a[i]
  31. a_copy = [a[j] for j in range(0, len(a)) if j != i]
  32. subresults = []
  33. permute(a_copy, subresults)
  34. for subresult in subresults:
  35. result = [element] + subresult
  36. results.insert(len(results), result)
  37. results = []
  38. permute(range(len(matrix)), results) # [0, 1, 2] for a 3x3 matrix
  39. After the call to permute(), the results matrix would look like this::
  40. [[0, 1, 2],
  41. [0, 2, 1],
  42. [1, 0, 2],
  43. [1, 2, 0],
  44. [2, 0, 1],
  45. [2, 1, 0]]
  46. You could then use that index matrix to loop over the original cost matrix
  47. and calculate the smallest cost of the combinations::
  48. n = len(matrix)
  49. minval = sys.maxint
  50. for row in range(n):
  51. cost = 0
  52. for col in range(n):
  53. cost += matrix[row][col]
  54. minval = min(cost, minval)
  55. print minval
  56. While this approach works fine for small matrices, it does not scale. It
  57. executes in O(*n*!) time: Calculating the permutations for an *n*\ x\ *n*
  58. matrix requires *n*! operations. For a 12x12 matrix, that's 479,001,600
  59. traversals. Even if you could manage to perform each traversal in just one
  60. millisecond, it would still take more than 133 hours to perform the entire
  61. traversal. A 20x20 matrix would take 2,432,902,008,176,640,000 operations. At
  62. an optimistic millisecond per operation, that's more than 77 million years.
  63. The Munkres algorithm runs in O(*n*\ ^3) time, rather than O(*n*!). This
  64. package provides an implementation of that algorithm.
  65. This version is based on
  66. http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html.
  67. This version was written for Python by Brian Clapper from the (Ada) algorithm
  68. at the above web site. (The ``Algorithm::Munkres`` Perl version, in CPAN, was
  69. clearly adapted from the same web site.)
  70. Usage
  71. =====
  72. Construct a Munkres object::
  73. from munkres import Munkres
  74. m = Munkres()
  75. Then use it to compute the lowest cost assignment from a cost matrix. Here's
  76. a sample program::
  77. from munkres import Munkres, print_matrix
  78. matrix = [[5, 9, 1],
  79. [10, 3, 2],
  80. [8, 7, 4]]
  81. m = Munkres()
  82. indexes = m.compute(matrix)
  83. print_matrix(matrix, msg='Lowest cost through this matrix:')
  84. total = 0
  85. for row, column in indexes:
  86. value = matrix[row][column]
  87. total += value
  88. print '(%d, %d) -> %d' % (row, column, value)
  89. print 'total cost: %d' % total
  90. Running that program produces::
  91. Lowest cost through this matrix:
  92. [5, 9, 1]
  93. [10, 3, 2]
  94. [8, 7, 4]
  95. (0, 0) -> 5
  96. (1, 1) -> 3
  97. (2, 2) -> 4
  98. total cost=12
  99. The instantiated Munkres object can be used multiple times on different
  100. matrices.
  101. Non-square Cost Matrices
  102. ========================
  103. The Munkres algorithm assumes that the cost matrix is square. However, it's
  104. possible to use a rectangular matrix if you first pad it with 0 values to make
  105. it square. This module automatically pads rectangular cost matrices to make
  106. them square.
  107. Notes:
  108. - The module operates on a *copy* of the caller's matrix, so any padding will
  109. not be seen by the caller.
  110. - The cost matrix must be rectangular or square. An irregular matrix will
  111. *not* work.
  112. Calculating Profit, Rather than Cost
  113. ====================================
  114. The cost matrix is just that: A cost matrix. The Munkres algorithm finds
  115. the combination of elements (one from each row and column) that results in
  116. the smallest cost. It's also possible to use the algorithm to maximize
  117. profit. To do that, however, you have to convert your profit matrix to a
  118. cost matrix. The simplest way to do that is to subtract all elements from a
  119. large value. For example::
  120. from munkres import Munkres, print_matrix
  121. matrix = [[5, 9, 1],
  122. [10, 3, 2],
  123. [8, 7, 4]]
  124. cost_matrix = []
  125. for row in matrix:
  126. cost_row = []
  127. for col in row:
  128. cost_row += [sys.maxint - col]
  129. cost_matrix += [cost_row]
  130. m = Munkres()
  131. indexes = m.compute(cost_matrix)
  132. print_matrix(matrix, msg='Highest profit through this matrix:')
  133. total = 0
  134. for row, column in indexes:
  135. value = matrix[row][column]
  136. total += value
  137. print '(%d, %d) -> %d' % (row, column, value)
  138. print 'total profit=%d' % total
  139. Running that program produces::
  140. Highest profit through this matrix:
  141. [5, 9, 1]
  142. [10, 3, 2]
  143. [8, 7, 4]
  144. (0, 1) -> 9
  145. (1, 0) -> 10
  146. (2, 2) -> 4
  147. total profit=23
  148. The ``munkres`` module provides a convenience method for creating a cost
  149. matrix from a profit matrix. Since it doesn't know whether the matrix contains
  150. floating point numbers, decimals, or integers, you have to provide the
  151. conversion function; but the convenience method takes care of the actual
  152. creation of the cost matrix::
  153. import munkres
  154. cost_matrix = munkres.make_cost_matrix(matrix,
  155. lambda cost: sys.maxint - cost)
  156. So, the above profit-calculation program can be recast as::
  157. from munkres import Munkres, print_matrix, make_cost_matrix
  158. matrix = [[5, 9, 1],
  159. [10, 3, 2],
  160. [8, 7, 4]]
  161. cost_matrix = make_cost_matrix(matrix, lambda cost: sys.maxint - cost)
  162. m = Munkres()
  163. indexes = m.compute(cost_matrix)
  164. print_matrix(matrix, msg='Lowest cost through this matrix:')
  165. total = 0
  166. for row, column in indexes:
  167. value = matrix[row][column]
  168. total += value
  169. print '(%d, %d) -> %d' % (row, column, value)
  170. print 'total profit=%d' % total
  171. References
  172. ==========
  173. 1. http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html
  174. 2. Harold W. Kuhn. The Hungarian Method for the assignment problem.
  175. *Naval Research Logistics Quarterly*, 2:83-97, 1955.
  176. 3. Harold W. Kuhn. Variants of the Hungarian method for assignment
  177. problems. *Naval Research Logistics Quarterly*, 3: 253-258, 1956.
  178. 4. Munkres, J. Algorithms for the Assignment and Transportation Problems.
  179. *Journal of the Society of Industrial and Applied Mathematics*,
  180. 5(1):32-38, March, 1957.
  181. 5. http://en.wikipedia.org/wiki/Hungarian_algorithm
  182. Copyright and License
  183. =====================
  184. This software is released under a BSD license, adapted from
  185. <http://opensource.org/licenses/bsd-license.php>
  186. Copyright (c) 2008 Brian M. Clapper
  187. All rights reserved.
  188. Redistribution and use in source and binary forms, with or without
  189. modification, are permitted provided that the following conditions are met:
  190. * Redistributions of source code must retain the above copyright notice,
  191. this list of conditions and the following disclaimer.
  192. * Redistributions in binary form must reproduce the above copyright notice,
  193. this list of conditions and the following disclaimer in the documentation
  194. and/or other materials provided with the distribution.
  195. * Neither the name "clapper.org" nor the names of its contributors may be
  196. used to endorse or promote products derived from this software without
  197. specific prior written permission.
  198. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  199. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  200. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  201. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  202. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  203. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  204. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  205. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  206. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  207. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  208. POSSIBILITY OF SUCH DAMAGE.
  209. """
  210. __docformat__ = 'restructuredtext'
  211. # ---------------------------------------------------------------------------
  212. # Imports
  213. # ---------------------------------------------------------------------------
  214. import sys
  215. # ---------------------------------------------------------------------------
  216. # Exports
  217. # ---------------------------------------------------------------------------
  218. __all__ = ['Munkres', 'make_cost_matrix']
  219. # ---------------------------------------------------------------------------
  220. # Globals
  221. # ---------------------------------------------------------------------------
  222. # Info about the module
  223. __version__ = "1.0.5.4"
  224. __author__ = "Brian Clapper, bmc@clapper.org"
  225. __url__ = "http://software.clapper.org/munkres/"
  226. __copyright__ = "(c) 2008 Brian M. Clapper"
  227. __license__ = "BSD-style license"
  228. # ---------------------------------------------------------------------------
  229. # Classes
  230. # ---------------------------------------------------------------------------
  231. class Munkres:
  232. """
  233. Calculate the Munkres solution to the classical assignment problem.
  234. See the module documentation for usage.
  235. """
  236. def __init__(self):
  237. """Create a new instance"""
  238. self.C = None
  239. self.row_covered = []
  240. self.col_covered = []
  241. self.n = 0
  242. self.Z0_r = 0
  243. self.Z0_c = 0
  244. self.marked = None
  245. self.path = None
  246. def make_cost_matrix(profit_matrix, inversion_function):
  247. """
  248. **DEPRECATED**
  249. Please use the module function ``make_cost_matrix()``.
  250. """
  251. import munkres
  252. return munkres.make_cost_matrix(profit_matrix, inversion_function)
  253. make_cost_matrix = staticmethod(make_cost_matrix)
  254. def pad_matrix(self, matrix, pad_value=0):
  255. """
  256. Pad a possibly non-square matrix to make it square.
  257. :Parameters:
  258. matrix : list of lists
  259. matrix to pad
  260. pad_value : int
  261. value to use to pad the matrix
  262. :rtype: list of lists
  263. :return: a new, possibly padded, matrix
  264. """
  265. max_columns = 0
  266. total_rows = len(matrix)
  267. for row in matrix:
  268. max_columns = max(max_columns, len(row))
  269. total_rows = max(max_columns, total_rows)
  270. new_matrix = []
  271. for row in matrix:
  272. row_len = len(row)
  273. new_row = row[:]
  274. if total_rows > row_len:
  275. # Row too short. Pad it.
  276. new_row += [0] * (total_rows - row_len)
  277. new_matrix += [new_row]
  278. while len(new_matrix) < total_rows:
  279. new_matrix += [[0] * total_rows]
  280. return new_matrix
  281. def compute(self, cost_matrix):
  282. """
  283. Compute the indexes for the lowest-cost pairings between rows and
  284. columns in the database. Returns a list of (row, column) tuples
  285. that can be used to traverse the matrix.
  286. :Parameters:
  287. cost_matrix : list of lists
  288. The cost matrix. If this cost matrix is not square, it
  289. will be padded with zeros, via a call to ``pad_matrix()``.
  290. (This method does *not* modify the caller's matrix. It
  291. operates on a copy of the matrix.)
  292. **WARNING**: This code handles square and rectangular
  293. matrices. It does *not* handle irregular matrices.
  294. :rtype: list
  295. :return: A list of ``(row, column)`` tuples that describe the lowest
  296. cost path through the matrix
  297. """
  298. self.C = self.pad_matrix(cost_matrix)
  299. self.n = len(self.C)
  300. self.original_length = len(cost_matrix)
  301. self.original_width = len(cost_matrix[0])
  302. self.row_covered = [False for i in range(self.n)]
  303. self.col_covered = [False for i in range(self.n)]
  304. self.Z0_r = 0
  305. self.Z0_c = 0
  306. self.path = self.__make_matrix(self.n * 2, 0)
  307. self.marked = self.__make_matrix(self.n, 0)
  308. done = False
  309. step = 1
  310. steps = { 1 : self.__step1,
  311. 2 : self.__step2,
  312. 3 : self.__step3,
  313. 4 : self.__step4,
  314. 5 : self.__step5,
  315. 6 : self.__step6 }
  316. while not done:
  317. try:
  318. func = steps[step]
  319. step = func()
  320. except KeyError:
  321. done = True
  322. # Look for the starred columns
  323. results = []
  324. for i in range(self.original_length):
  325. for j in range(self.original_width):
  326. if self.marked[i][j] == 1:
  327. results += [(i, j)]
  328. return results
  329. def __copy_matrix(self, matrix):
  330. """Return an exact copy of the supplied matrix"""
  331. return copy.deepcopy(matrix)
  332. def __make_matrix(self, n, val):
  333. """Create an *n*x*n* matrix, populating it with the specific value."""
  334. matrix = []
  335. for i in range(n):
  336. matrix += [[val for j in range(n)]]
  337. return matrix
  338. def __step1(self):
  339. """
  340. For each row of the matrix, find the smallest element and
  341. subtract it from every element in its row. Go to Step 2.
  342. """
  343. C = self.C
  344. n = self.n
  345. for i in range(n):
  346. minval = min(self.C[i])
  347. # Find the minimum value for this row and subtract that minimum
  348. # from every element in the row.
  349. for j in range(n):
  350. self.C[i][j] -= minval
  351. return 2
  352. def __step2(self):
  353. """
  354. Find a zero (Z) in the resulting matrix. If there is no starred
  355. zero in its row or column, star Z. Repeat for each element in the
  356. matrix. Go to Step 3.
  357. """
  358. n = self.n
  359. for i in range(n):
  360. for j in range(n):
  361. if (self.C[i][j] == 0) and \
  362. (not self.col_covered[j]) and \
  363. (not self.row_covered[i]):
  364. self.marked[i][j] = 1
  365. self.col_covered[j] = True
  366. self.row_covered[i] = True
  367. self.__clear_covers()
  368. return 3
  369. def __step3(self):
  370. """
  371. Cover each column containing a starred zero. If K columns are
  372. covered, the starred zeros describe a complete set of unique
  373. assignments. In this case, Go to DONE, otherwise, Go to Step 4.
  374. """
  375. n = self.n
  376. count = 0
  377. for i in range(n):
  378. for j in range(n):
  379. if self.marked[i][j] == 1:
  380. self.col_covered[j] = True
  381. count += 1
  382. if count >= n:
  383. step = 7 # done
  384. else:
  385. step = 4
  386. return step
  387. def __step4(self):
  388. """
  389. Find a noncovered zero and prime it. If there is no starred zero
  390. in the row containing this primed zero, Go to Step 5. Otherwise,
  391. cover this row and uncover the column containing the starred
  392. zero. Continue in this manner until there are no uncovered zeros
  393. left. Save the smallest uncovered value and Go to Step 6.
  394. """
  395. step = 0
  396. done = False
  397. row = -1
  398. col = -1
  399. star_col = -1
  400. while not done:
  401. (row, col) = self.__find_a_zero()
  402. if row < 0:
  403. done = True
  404. step = 6
  405. else:
  406. self.marked[row][col] = 2
  407. star_col = self.__find_star_in_row(row)
  408. if star_col >= 0:
  409. col = star_col
  410. self.row_covered[row] = True
  411. self.col_covered[col] = False
  412. else:
  413. done = True
  414. self.Z0_r = row
  415. self.Z0_c = col
  416. step = 5
  417. return step
  418. def __step5(self):
  419. """
  420. Construct a series of alternating primed and starred zeros as
  421. follows. Let Z0 represent the uncovered primed zero found in Step 4.
  422. Let Z1 denote the starred zero in the column of Z0 (if any).
  423. Let Z2 denote the primed zero in the row of Z1 (there will always
  424. be one). Continue until the series terminates at a primed zero
  425. that has no starred zero in its column. Unstar each starred zero
  426. of the series, star each primed zero of the series, erase all
  427. primes and uncover every line in the matrix. Return to Step 3
  428. """
  429. count = 0
  430. path = self.path
  431. path[count][0] = self.Z0_r
  432. path[count][1] = self.Z0_c
  433. done = False
  434. while not done:
  435. row = self.__find_star_in_col(path[count][1])
  436. if row >= 0:
  437. count += 1
  438. path[count][0] = row
  439. path[count][1] = path[count-1][1]
  440. else:
  441. done = True
  442. if not done:
  443. col = self.__find_prime_in_row(path[count][0])
  444. count += 1
  445. path[count][0] = path[count-1][0]
  446. path[count][1] = col
  447. self.__convert_path(path, count)
  448. self.__clear_covers()
  449. self.__erase_primes()
  450. return 3
  451. def __step6(self):
  452. """
  453. Add the value found in Step 4 to every element of each covered
  454. row, and subtract it from every element of each uncovered column.
  455. Return to Step 4 without altering any stars, primes, or covered
  456. lines.
  457. """
  458. minval = self.__find_smallest()
  459. for i in range(self.n):
  460. for j in range(self.n):
  461. if self.row_covered[i]:
  462. self.C[i][j] += minval
  463. if not self.col_covered[j]:
  464. self.C[i][j] -= minval
  465. return 4
  466. def __find_smallest(self):
  467. """Find the smallest uncovered value in the matrix."""
  468. minval = sys.maxint
  469. for i in range(self.n):
  470. for j in range(self.n):
  471. if (not self.row_covered[i]) and (not self.col_covered[j]):
  472. if minval > self.C[i][j]:
  473. minval = self.C[i][j]
  474. return minval
  475. def __find_a_zero(self):
  476. """Find the first uncovered element with value 0"""
  477. row = -1
  478. col = -1
  479. i = 0
  480. n = self.n
  481. done = False
  482. while not done:
  483. j = 0
  484. while True:
  485. if (self.C[i][j] == 0) and \
  486. (not self.row_covered[i]) and \
  487. (not self.col_covered[j]):
  488. row = i
  489. col = j
  490. done = True
  491. j += 1
  492. if j >= n:
  493. break
  494. i += 1
  495. if i >= n:
  496. done = True
  497. return (row, col)
  498. def __find_star_in_row(self, row):
  499. """
  500. Find the first starred element in the specified row. Returns
  501. the column index, or -1 if no starred element was found.
  502. """
  503. col = -1
  504. for j in range(self.n):
  505. if self.marked[row][j] == 1:
  506. col = j
  507. break
  508. return col
  509. def __find_star_in_col(self, col):
  510. """
  511. Find the first starred element in the specified row. Returns
  512. the row index, or -1 if no starred element was found.
  513. """
  514. row = -1
  515. for i in range(self.n):
  516. if self.marked[i][col] == 1:
  517. row = i
  518. break
  519. return row
  520. def __find_prime_in_row(self, row):
  521. """
  522. Find the first prime element in the specified row. Returns
  523. the column index, or -1 if no starred element was found.
  524. """
  525. col = -1
  526. for j in range(self.n):
  527. if self.marked[row][j] == 2:
  528. col = j
  529. break
  530. return col
  531. def __convert_path(self, path, count):
  532. for i in range(count+1):
  533. if self.marked[path[i][0]][path[i][1]] == 1:
  534. self.marked[path[i][0]][path[i][1]] = 0
  535. else:
  536. self.marked[path[i][0]][path[i][1]] = 1
  537. def __clear_covers(self):
  538. """Clear all covered matrix cells"""
  539. for i in range(self.n):
  540. self.row_covered[i] = False
  541. self.col_covered[i] = False
  542. def __erase_primes(self):
  543. """Erase all prime markings"""
  544. for i in range(self.n):
  545. for j in range(self.n):
  546. if self.marked[i][j] == 2:
  547. self.marked[i][j] = 0
  548. # ---------------------------------------------------------------------------
  549. # Functions
  550. # ---------------------------------------------------------------------------
  551. def make_cost_matrix(profit_matrix, inversion_function):
  552. """
  553. Create a cost matrix from a profit matrix by calling
  554. 'inversion_function' to invert each value. The inversion
  555. function must take one numeric argument (of any type) and return
  556. another numeric argument which is presumed to be the cost inverse
  557. of the original profit.
  558. This is a static method. Call it like this:
  559. .. python::
  560. cost_matrix = Munkres.make_cost_matrix(matrix, inversion_func)
  561. For example:
  562. .. python::
  563. cost_matrix = Munkres.make_cost_matrix(matrix, lambda x : sys.maxint - x)
  564. :Parameters:
  565. profit_matrix : list of lists
  566. The matrix to convert from a profit to a cost matrix
  567. inversion_function : function
  568. The function to use to invert each entry in the profit matrix
  569. :rtype: list of lists
  570. :return: The converted matrix
  571. """
  572. cost_matrix = []
  573. for row in profit_matrix:
  574. cost_matrix.append([inversion_function(value) for value in row])
  575. return cost_matrix
  576. def print_matrix(matrix, msg=None):
  577. """
  578. Convenience function: Displays the contents of a matrix of integers.
  579. :Parameters:
  580. matrix : list of lists
  581. Matrix to print
  582. msg : str
  583. Optional message to print before displaying the matrix
  584. """
  585. import math
  586. if msg is not None:
  587. print msg
  588. # Calculate the appropriate format width.
  589. width = 0
  590. for row in matrix:
  591. for val in row:
  592. width = max(width, int(math.log10(val)) + 1)
  593. # Make the format string
  594. format = '%%%dd' % width
  595. # Print the matrix
  596. for row in matrix:
  597. sep = '['
  598. for val in row:
  599. sys.stdout.write(sep + format % val)
  600. sep = ', '
  601. sys.stdout.write(']\n')
  602. # ---------------------------------------------------------------------------
  603. # Main
  604. # ---------------------------------------------------------------------------
  605. if __name__ == '__main__':
  606. matrices = [
  607. # Square
  608. ([[400, 150, 400],
  609. [400, 450, 600],
  610. [300, 225, 300]],
  611. 850 # expected cost
  612. ),
  613. # Rectangular variant
  614. ([[400, 150, 400, 1],
  615. [400, 450, 600, 2],
  616. [300, 225, 300, 3]],
  617. 452 # expected cost
  618. ),
  619. # Square
  620. ([[10, 10, 8],
  621. [ 9, 8, 1],
  622. [ 9, 7, 4]],
  623. 18
  624. ),
  625. # Rectangular variant
  626. ([[10, 10, 8, 11],
  627. [ 9, 8, 1, 1],
  628. [ 9, 7, 4, 10]],
  629. 15
  630. ),
  631. ]
  632. m = Munkres()
  633. for cost_matrix, expected_total in matrices:
  634. print_matrix(cost_matrix, msg='cost matrix')
  635. indexes = m.compute(cost_matrix)
  636. total_cost = 0
  637. for r, c in indexes:
  638. x = cost_matrix[r][c]
  639. total_cost += x
  640. print '(%d, %d) -> %d' % (r, c, x)
  641. print 'lowest cost=%d' % total_cost
  642. assert expected_total == total_cost