数模竞赛-线性规划模型

线性规划

例题1:求解:

$$
\displaylines{
\max z=70x_1+50x_2+60x_3,\\
\mathrm{s.t.}\begin{cases}
2x_1+4x_2+3x_3\leqslant150,\\
3x_1+x_2+5x_3\leqslant160,\\
7x_1+3x_2+5x_3\leqslant200,\\
x_i\geqslant0,i=1,2,3.
\end{cases}
}
$$

代码:

1
2
3
4
5
6
7
8
9
10
11
#pip install cvxpy cvxpy[GLPK_MI] cvxopt
import cvxpy,numpy
c=numpy.array([70,50,60])
a=numpy.array([[2,4,3],[3,1,5],[7,3,5]])
b=numpy.array([150,160,200])
x=cvxpy.Variable(3,pos=True) #决策变量 列向量
obj=cvxpy.Maximize(c@x)
cons=[a@x<=b]
prob=cvxpy.Problem(obj,cons)
prob.solve(solver='GLPK_MI')
print(x.value,prob.value) #最优解 和 最优值z

例题2:求解:

$$
\displaylines{
\max z=1.15x_{41}+1.40x_{23}+1.25x_{32}+1.06x_{54},\\
\mathrm{s.t.}\begin{cases}
x_{11}+x_{14}=100000,\\
x_{21}+x_{23}+x_{24}=1.06x_{14},\\
x_{31}+x_{32}+x_{34}=1.15x_{21}+1.06x_{34},\\
x_{54}=1.15x_{31}+1.06x_{44},\\
x_{32}\leqslant40000,x_{23}\leqslant30000,\\
x_{ij}\geqslant0;i=1,2,3,4,5;j=1,2,3,4.
\end{cases}
}
$$

代码:

1
2
3
4
5
6
7
8
9
10
11
12
import cvxpy
x=cvxpy.Variable((5,4),pos=True)
obj=cvxpy.Maximize(1.15*x[3,0]+1.40*x[1,2]+1.25*x[2,1]+1.06*x[4,3])
cons=[x[0,0]+x[0,3]==100000,
x[1,0]+x[1,2]+x[1,3]==1.06*x[0,3],
x[2,0]+x[2,1]+x[2,3]==1.15*x[0,0]+1.06*x[1,3],
x[3,0]+x[3,3]==1.15*x[1,0]+1.06*x[2,3],
x[4,3]==1.15*x[2,0]+1.06*x[3,3],
x[2,1]<=40000,x[1,2]<=30000]
prob=cvxpy.Problem(obj,cons)
prob.solve(solver='GLPK_MI')
print(prob.value,x.value)

例题3:求解:

$$
\displaylines{
\min z=2800(x_{11}+x_{21}+x_{31}+x_{41})+4500(x_{12}+x_{22}+x_{32})+6000(x_{13}+x_{23})+7300x_{14},\\
\mathrm{s.t.}\begin{cases}
x_{11}+x_{12}+x_{13}+x_{14}\geqslant15,\\
x_{12}+x_{13}+x_{14}+x_{21}+x_{22}+x_{23}\geqslant10,\\
x_{13}+x_{14}+x_{22}+x_{23}+x_{31}+x_{32}\geqslant20,\\
x_{14}+x_{23}+x_{32}+x_{41}\geqslant12,\\
x_{ij}\geqslant0;i=1,2,3,4;j=1,2,3,4.
\end{cases}
}
$$

代码:

1
2
3
4
5
6
7
8
9
10
import cvxpy
x=cvxpy.Variable((4,4),pos=True)
obj=cvxpy.Minimize(2800*sum(x[:,0])+4500*sum(x[:3,1])+6000*sum(x[:2,2])+7300*x[0,3])
cons=[sum(x[0,:])>=15,
sum(x[0,1:])+sum(x[2,:3])>=10,
sum(x[0,2:])+sum(x[1,1:3])+sum(x[2,:2])>=20,
x[0,3]+x[1,2]+x[2,1]+x[3,0]>=12]
prob=cvxpy.Problem(obj,cons)
prob.solve(solver='GLPK_MI')
print(prob.value,x.value)

整数规划

例题:

$$
\displaylines{
\min z=\sum_{i=1}^6x_i,\\
\mathrm{s.t.}\begin{cases}
x_1+x_6\geqslant35,\\
x_1+x_2\geqslant40,\\
x_2+x_3\geqslant50,\\
x_3+x_4\geqslant45,\\
x_4+x_5\geqslant55,\\
x_5+x_6\geqslant30,\\
x_i\geqslant0,x_i\in\mathbb Z,i=1,2,\cdots,6.
\end{cases}
}
$$

代码:

1
2
3
4
5
6
7
8
9
10
import cvxpy,numpy
a=numpy.array([35,40,50,45,55,30])
x=cvxpy.Variable(6,integer=True)
obj=cvxpy.Minimize(sum(x))
cons=[x>=0]
for i in range(6):
cons.append(x[(i-1)%6]+x[i]>=a[i])
prob=cvxpy.Problem(obj,cons)
prob.solve(solver='GLPK_MI')
print(prob.value,x.value)