主题:背包问题
163111511
[专家分:90] 发布于 2005-08-05 17:39:00
随机出现十种物品,每个重量100千克以内。设定一个背包的载重上限,计算出一种装物品的方法使物品重量正好等于背包载重上限。
回复列表 (共2个回复)
沙发
Matodied [专家分:7560] 发布于 2007-04-21 21:44:00
你的意思是不是这样:有十种物品,每种都有足够多个,现要求选出一些物品,使背包正好装满。
CLS
INPUT "Carry weight:"; n
DIM w(10), s(1000), t(1000)
FOR i = 1 TO 10: INPUT w(i): NEXT i
a = 0: n0 = n: p = 0
FOR i = 1 TO 9: FOR j = i + 1 TO 10
IF a(i) < a(j) THEN SWAP a(i), a(j)
NEXT j, i
DO
a = a + 1
IF a <= 10 THEN
t = w(a)
IF t <= n THEN
p = p + 1: s(p) = a: t(p) = t: n = n - t
IF p = 1 THEN v = 1 ELSE v = 0
END IF
ELSE
a = s(p): n = n + t(p): p = p - 1
END IF
LOOP UNTIL p = 0 AND v = 0 AND n = n0 OR n = 0
IF p = 0 AND v = 0 AND n = n0 THEN
PRINT "Not solve."
ELSE
PRINT "Weight:"; : FOR i = 1 TO p: PRINT t(i); : NEXT i
END IF
END
板凳
小小DAVID [专家分:300] 发布于 2009-11-14 13:28:00
饿哦定
我来回复