Advertisement
VisualPaul

solving linear program with 2 variables

Apr 4th, 2015
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. from __future__ import division
  2.  
  3. c, p, q, r, s = map(int, raw_input().split())
  4. inf = float('inf')
  5.  
  6. def solve1(c, a, b, L, U):
  7.     U = min(U, b // a)
  8.     if c >= 0:
  9.         return U
  10.     else:
  11.         return max(0, L)            
  12.  
  13. def solve(c1, c2, a1, a2, b, L, U):
  14.     if b < 0:
  15.         return (-inf, -inf)
  16.     def value((x, y)):
  17.         return c1 * x + c2 * y
  18.     if c1 <= 0:
  19.         return (L, solve1(c2, a2, b - a1 * L, 0, inf))
  20.     elif c2 <= 0:
  21.         return (solve1(c1, a1, b, L, U), 0)
  22.     elif a1 == 0:
  23.         return (U, solve1(c2, a2, b, 0, inf))
  24.     elif a2 == 0:
  25.         return (0, inf)
  26.     elif L == U:
  27.         return (L, solve1(c2, a2, b - a1 * L, 0, inf))
  28.     elif b == 0:
  29.         return (0, 0)
  30.     else:
  31.         if U != inf:
  32.             U = min(U, b // a1)
  33.         if L != 0 or U != inf:
  34.             xp, yp = solve(c1, c2, a1, a2, b - ((b - a1 * U + a2 - 1) // a2) * a2 - a1 * L, 0, inf)
  35.             xp += L
  36.             yp += (b - a1 * U + a2 - 1) // a2
  37.             return max((U, (b - a1 * U) // a2), (xp, yp), key=value)
  38.         if a1 < a2:
  39.             x, y = solve(c2, c1, a2, a1, b, 0, inf)
  40.             return y, x
  41.         k = a1 // a2
  42.         p = a1 - k * a2
  43.         x, y = solve(c1 - c2 * k, c2, p, a2, b - k * (b // a1) * a2, 0, b // a1)
  44.         y -= k *x
  45.         y += (b // a1) * k
  46.         return x, y
  47.  
  48. x, y = solve(p, q, r, s, c, 0, inf)
  49. print x * p + q * y
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement