import cvxpy as cp
import numpy as np
M = 10000
t = np.array([210, 300, 100, 130, 260])
s = np.array([150, 210, 60, 80, 180])
x = cp.Variable(5, integer=True)
obj = cp.Maximize(cp.sum(cp.multiply(x, s)))
con = [x[0] + x[1] + x[2] == 1, x[2] + x[3] == 1,
cp.sum(cp.multiply(x, t)) <= 600, x[4] <= x[0] * M, x <= 1, x >= 0]
prob = cp.Problem(obj, con)
prob.solve(solver='GLPK_MI')
print("最优值为:", prob.value)
print("最优解为:", x.value)
import cvxpy as cp
import numpy as np
w = np.array([8, 13, 6, 9, 5, 7])
s = np.array([3, 5, 2, 4, 2, 3])
x = cp.Variable(6, integer=True)
obj = cp.Maximize(cp.sum(cp.multiply(x, s)))
con = [cp.sum(cp.multiply(x, w)) <= 24, x >= 0, x <= 1]
prob = cp.Problem(obj, con)
prob.solve(solver='GLPK_MI')
print("最优值为:", prob.value)
print("最优解为:", x.value)
c1 = np.array([0.2, 0.2, 0.2])
c2 = np.array([58, 54, 50])
a = np.array([[-1, 0, 0], [-1, -1, 0]])
b = np.array([-40, -100])
x = cp.Variable(3, integer=True)
obj = cp.Minimize(c1 @ x ** 2 + c2 @ x - 560)
con = [x >= 0, x <= 100, x[0] >= 40, x[0] + x[1] >= 100, x[0] + x[1] + x[2] == 180, a @ x <= b]
prob = cp.Problem(obj, con)
prob.solve(solver='CPLEX')
print("最优值为:", prob.value)
print("最优解为:", x.value)
x = cp.Variable(3, integer=False)
obj = lambda x: (x[0] + 4 * x[1] + 5 * x[2]) * x[0] + (4 * x[0] + 2 * x[1] + 6 * x[2]) * x[1] + (5 * x[0] + 6 * x[1] + 3 * x[2]) * x[2]
con = [x[0] ** 2 + x[1] ** 2 + x[2] ** 2 == 1]
cons = {'type': 'eq', 'fun': lambda x: x[0] ** 2 + x[1] ** 2 + x[2] ** 2 - 1}
# prob = cp.Problem(obj, con)
# bd = [(-1, 1) for i in range(0, 3)]
LB = [-1] * 3;
UB = [1] * 3
bound = tuple(zip(LB, UB))
res = minimize(obj, np.ones(3), constraints=cons, bounds=bound)
print(res.fun, '\n', res.success, '\n', res.x) # 输出最优值、求解状态、最优解