如何在Pulp BinPacking中添加约束,确保物品a与b不分配至同一箱子
Got it, let's break this down clearly—this is a common constraint to add in bin packing problems, and it's straightforward once you map it to your Pulp variable setup.
First, let's align on the typical variable structure most people use for bin packing in Pulp (if your existing code uses something similar, this will plug right in):
x[i][j]: Binary variable wherex[i][j] = 1means itemiis placed in binj, and 0 otherwise.y[j]: Binary variable wherey[j] = 1means binjis being used, 0 otherwise.
The Core Constraint Logic
To make sure items a and b never share a bin, we just need to enforce that for every single bin j, at most one of a or b can be assigned to it. Translating that into a linear constraint Pulp understands:x[a][j] + x[b][j] ≤ 1 for all bins j.
Implementing This in Your Code
Let's say you already have:
- A list of items (e.g.,
items = [a, b, c, d, ...]whereaandbare your target items) - A list of bins (e.g.,
bins = list(range(total_bins))) - Your Pulp
LpProbleminstance namedprob
Add this loop to your constraint-defining section:
# Replace a and b with the actual identifiers (indices or IDs) from your code for j in bins: prob += pulp.LpConstraint( x[a][j] + x[b][j], pulp.LpConstraintLE, 1, name=f"no_co_bin_{a}_{b}_bin_{j}" )
Quick Breakdown
- For every bin
j, we cap the sum ofx[a][j]andx[b][j]at 1. Since both are binary (0 or 1), this means they can't both be 1 in the same bin—exactly what you need. - The
nameparameter is optional but super helpful for debugging if you ever need to inspect or tweak constraints later.
If Your Variable Setup Is Different
If you're using an integer variable for bin assignment (e.g., bin_assignment[i] which stores the bin number for item i), you can't use a direct != in Pulp. Instead, use this alternative approach:
for j in bins: # Ensure a and b aren't both assigned to bin j prob += pulp.LpConstraint( (bin_assignment[a] == j) + (bin_assignment[b] == j) ≤ 1, name=f"no_same_bin_{j}" )
Just drop this constraint block into your code after defining your variables and before calling prob.solve(), and it'll enforce that items a and b stay in separate bins.
内容的提问来源于stack exchange,提问作者Ankita Samariya

