租车原则是首先考虑自带经费多的部分同学优先租相对花费少的自行车,尽量少花学校经费以达到最多同学租车的结果。比如学生带的钱为9,3,6,7,5,租车的钱分别需要15,8,12,6,9,11,如果5个人都能租车,至少需要学校提供经费为(6-3)+(8-5)+(9-6)+(11-7)+(12-9)=16,如果学校经费只有10元,则自带钱最少的同学不租车,这时所需学校经费为(6-5)+(8-6)+(9-7)+(11-9)=7。计算过程中采用二分查找法来判断租用自行车的人数能否达到最大值。
Dim a( 1 To 100) As Integer, b( 1 To 100) As Integer
Dim n As Integer, m As Integer
Private Sub Command1_Click()
Dim left As Integer, right As Integer, mid As Integer, an s As Integer
n=Val(Text 1.Text) :m=Val(Text 2.Text)
‘从数据库读取n位同学带的钱存储在数组a,m辆自行车租用的钱存储在数组b,代码略。
Call px(a(),n)
Call px(b(),m)
left =1:right=n:ans= 0
Do While left<=right
mid=(left+right) \ 2
If check(mid) =True Then
①
right =mid-1
Else
left =mid+ 1
End If
Loop
Label 1.Caption=“能租车的最大人数为”+Str(ans)
End Sub
Sub px(d() As Integer, s As Integer)
Dimi as integer, j as integer, k as integer
For i=2Tos
k=d(i)
j=i-1
Do While k<d(j)
d(j+1)=d(j)
j=j-1
If j=0ThenExitDo
Loop
②
Next i
End Sub
Function check(mid As Integer) As Boolean
Dim cnt As Integer, jf As Integer, t As Integer
cnt=Val(Text 3.Text)
For t=1Ton-mid+ 1
If b(t) >a(mid+t-1) Then jf=b(t) -a(mid+t-1) Else jf= 0
③
Next t
If cnt>= 0 Then check=True
End Function
① ② ③