我写了个背包问题,好象已经解决了-->multiple1902转移
我刚写的背包问题,在测试一些数据时出现了点问题,麻烦高手指点一下!Dim p, x, y As Integer
Private Sub Form_click()
y = InputBox("input y , 1<y<100") '输入值,y表示物品数,p表示最大承受物品能力,a(1,y)表示各个背包所拥有的
p = InputBox("input p") 物品数,a(2,y)表示各个背包的价值
Dim a(1 To 100, 1 To 100) As Integer
For i = 1 To 2
For j = 1 To y
a(i, j) = InputBox("input a(i, j)")
Next
Next
j = 2
Do '升序排列
For i = j To y
If a(1, j - 1) > a(1, i) Then
t = a(1, j - 1)
a(1, j - 1) = a(1, i)
a(1, i) = t
t = a(2, j - 1)
a(2, j - 1) = a(2, i)
a(2, i) = t
End If
Next i
j = j + 1
Loop Until j > y
Dim max As Integer
Dim m As Integer
Dim n As Integer
Dim k As Integer
max = 0
m = 0
n = 0
k = 1
Call try(p, max, m, n, k, a())
Print max
End Sub
Private Sub try(ByVal p As Integer, ByRef max As Integer, ByVal m As Integer, ByVal n As Integer, ByVal k As Integer, ByRef a() As Integer)
For i = k To y
If m + a(1, i) <= p Then
m = m + a(1, i)
n = n + a(2, i)
k = i
Else
Exit For
End If
Next i
If n > max Then
max = n
End If
m = m - a(1, k)
n = n - a(2, k)
k = k - 1
If k > 0 Then
Call try(p, max, m, n, k, a())
End If
End Sub
当 y=5且数组a()各项都为 1 ,p=10 时,便出现了错误,本来应该输出5,它却输出了10,也就是p的值
[此贴子已经被作者于2007-8-29 11:50:56编辑过]