例如:若n=4,4个仓库中的疫苗数分别为50、13、80、27。若m=2,最小差值为10;若m=3,最小差值为40。
编写VB程序模拟上述功能,在文本框Text1中输入n(n≤15),在文本框Text2中输入m(m≤4),随机生成n个两位正整数,在列表框List1中输出。单击“计算”按钮Command1,在文本框Text3中输出最小差值,在列表框List2中输出每个国家获得疫苗的方案。程序运行界面如图所示。
Private Sub Command1_Click()
Const maxn = 15
Dim n As Integer, i As Long, j As Long, k As Long, p As Integer, m As Integer
Dim a(1 To maxn) As Long, f(1 To maxn) As Long
Dim s(1 To maxn) As String, max As Long, min As Long, ans As Long, ansi As Long
n = Val(Text1.Text): m = Val(Text2.Text)
List1.Clear: List2.Clear: Randomize
For i = 1 To n
①
List1.AddItem Str(a(i))
Next i
ans = 10000
For i = 1 To m ^ n '枚举所有的分配方案
For j = 1 To m
f(j) = 0
Next j
j = i: max = 0: min = 10000
For k = 1 To n
f(p) = f(p) + a(k)
j = j \ m
Next k
For k = 1 To m
If f(k) > max Then max = f(k)
If f(k) < min Then min = f(k)
Next k
If ② Then
ans = max - min
③
End If
Next i
Text3.Text = Str(ans)
For i = 1 To n
j = ansi Mod m
s(j + 1) = s(j + 1) + Str(a(i))
ansi = ansi \ m
Next i
For i = 1 To m
List2.AddItem s(i)
Next i
End Sub
① ② ③