跳到主要内容

数学 04 · 运筹优化:背包、指派与整数规划

运筹学的价值不在「求一个最优解」,而在知道最优解离贪心有多远。本节用三个经典问题把这件事量出来:0-1 背包的 DP 与贪心的差距、指派问题的暴搜/状压 DP 与贪心的差距、以及线性规划松弛与整数解之间的「取整陷阱」。

1. 0-1 背包:DP 换最优,贪心换速度​

DP 复杂度 ,贪心(按性价比排序)是 但只能保证近似。差距有多大?直接跑随机实例看平均。

import numpy as np
np.set_printoptions(precision=3, suppress=True)
rng = np.random.default_rng(0)

def knap_dp(items, W):
dp = np.zeros(W + 1)
for w, v in items:
for cap in range(W, w - 1, -1):
dp[cap] = max(dp[cap], dp[cap - w] + v)
return dp[W]

def knap_greedy(items, W):
order = sorted(items, key=lambda x: -x[1] / x[0])
total_w = total_v = 0
for w, v in order:
if total_w + w <= W:
total_w += w; total_v += v
return total_v

gaps = []
print(f"{'实例':<6}{'n':<5}{'W':<6}{'DP 最优':<10}{'贪心':<10}{'差距'}")
print("-" * 46)
for k in range(8):
n = 10
W = 50
items = [(int(rng.integers(5, 25)), int(rng.integers(10, 60))) for _ in range(n)]
opt, g = knap_dp(items, W), knap_greedy(items, W)
gaps.append((opt - g) / opt)
print(f"{k:<6}{n:<5}{W:<6}{opt:<10}{g:<10}低于最优 {gaps[-1]:.1%}")

print(f"\n平均落后最优 {np.mean(gaps):.1%},最差 {np.max(gaps):.1%}")
print("结论:n 小、W 小 → DP 直接最优;n 上万(选品/装箱)→ DP 的 O(nW) 撑不住,改用贪心 + 局部搜索或 ILP 求解器。")
# 指派问题:暴搜 / 状压 DP / 贪心,三条路的代价
from itertools import permutations

def assign_brute(C):
n = C.shape[0]
best, best_perm = float('inf'), None
for perm in permutations(range(n)):
cost = sum(C[i, perm[i]] for i in range(n))
if cost < best:
best, best_perm = cost, perm
return best, best_perm

def assign_dp(C):
n = C.shape[0]
INF = 1e18
dp = np.full(1 << n, INF); dp[0] = 0
for mask in range(1 << n):
i = bin(mask).count('1')
if i >= n: continue
for j in range(n):
if not (mask >> j) & 1 and dp[mask] + C[i, j] < dp[mask | (1 << j)]:
dp[mask | (1 << j)] = dp[mask] + C[i, j]
return dp[(1 << n) - 1]

def assign_greedy(C):
n = C.shape[0]; used = set(); total = 0
for i in range(n):
j = min((j for j in range(n) if j not in used), key=lambda j: C[i, j])
used.add(j); total += C[i, j]
return total

n = 8
C = rng.integers(1, 20, size=(n, n))
opt, perm = assign_brute(C)
dp_val = assign_dp(C)
g_val = assign_greedy(C)
print(f"n={n},暴搜最优={opt}({perm}),状压 DP={dp_val},贪心={g_val}(差距 {(g_val-opt)/opt:+.1%})")
print(f"搜索空间 8!=40320,状压 DP 状态数 2^8={1<<n}")
print("\n现实规模(千人级任务分配)两条路都不可行 → 用 Hungarian O(n³) 或 OR-Tools 的 min-cost-flow。")
# 线性规划松弛与取整陷阱:2 变量 LP 顶点枚举 + 整数可行性
from itertools import combinations
import math as m

def lp_vertices(c, A, b):
"""枚举约束交点,保留可行点,返回最优(max c·x)"""
lines = list(range(len(A)))
best = None
for i, j in combinations(lines, 2):
M = np.array([A[i], A[j]], float)
if abs(np.linalg.det(M)) < 1e-12: continue
x = np.linalg.solve(M, np.array([b[i], b[j]], float))
if all(A @ x <= np.array(b) + 1e-9):
val = c @ x
if best is None or val > best[0]:
best = (val, x)
return best

# max 5x+4y s.t. 2x+3y<=6, x<=2, y<=2
c = np.array([5.0, 4.0])
A = np.array([[2, 3], [1, 0], [0, 1], [-1, 0], [0, -1]], float)
b = np.array([6, 2, 2, 0, 0], float)
val, x = lp_vertices(c, A, b)
print(f"LP 最优:x={x},目标={val:.3f}")
rnd = np.round(x)
print(f"直接四舍五入 → {rnd},可行性 {bool(all(A @ rnd <= b + 1e-9))}(越界!)")
flr = np.floor(x)
print(f"向下取整 → {flr},目标={c @ flr:.1f},可行 {bool(all(A @ flr <= b + 1e-9))}")
int_best = max(((c @ np.array([i, j]), (i, j)) for i in range(3) for j in range(3)
if all(A @ np.array([i, j]) <= b)), key=lambda t: t[0])
print(f"整数最优 → {int_best[1]},目标={int_best[0]:.1f}")
print(f"\nMIP gap = {(val - int_best[0]) / val:.1%}:LP 松弛是整数规划的上界,差距越大越难砍。")
print("OR-Tools 的 CP-SAT/GLOP 就是这条流水线:先解 LP 松弛,再 branch-and-bound 收紧。")

# 单机调度:Smith 规则(按 p/w 排序)为什么最优
jobs = [(2, 4), (3, 9), (1, 1), (4, 8)] # (加工时长 p, 权重 w)
def wct(seq): # 加权完成时间
t, s = 0, 0
for i in seq:
t += jobs[i][0]; s += t * jobs[i][1]
return s
smith = sorted(range(len(jobs)), key=lambda i: jobs[i][0] / jobs[i][1])
print(f"\nSmith 规则排序={smith},加权完成时间={wct(smith)}")
best = min(((wct(seq), seq) for seq in permutations(range(len(jobs)))), key=lambda t: t[0])
print(f"全排列最优={best[0]}(序列 {best[1]})——两者相等,验证了『短加工/高权重优先』的最优性。")

2. 三个问题共同的骨架​

问题精确解法复杂度何时放弃精确
0-1 背包DP 是金额/容量上亿(伪多项式爆炸)
指派Hungarian / min-cost flow有额外约束(时窗、技能匹配)→ ILP
排产/选址MILP / CP-SAT指数最坏规模超过 变量 → 启发式 + 下界评估

站内关联与参考来源​