子題2(11%):如果有一個客人來買這個菜攤的n 項商品,每類商品只能買1 項或不買,請
選手列出所有可能的購買組合。輸出之順序,應依照購買之總金額由高而低依序輸出。
輸入說明:
第1 行有1 個數字,代表n 的值。
第2 行有4 組數字,以逗號隔開,分別表示「肉」、「菜」、「蛋」、「果」每項商品的購買金額。
輸出說明:
每列輸出一組購買組合及其購買總金額,並至少以1 個空白隔開。其輸出方式為:每列均輸
出「肉菜蛋果」字串,但客人「購買」之商品名稱以「小括號」括起來。輸出之順序依購買
之總金額由高而低依序輸出,若有總金額相同者則不限順序。
輸入範例:【檔名:in-4-2.txt】
2
140, 64, 36, 84
輸出範例:【檔名:out-4-2.txt】
(肉)菜蛋(果) 224
(肉)(菜)蛋果 204
(肉)菜(蛋)果 176
肉(菜)蛋(果) 148
肉菜(蛋)(果) 120
肉(菜)(蛋)果 100
Dim X() As String
回覆刪除Dim Y() As String
Dim N
Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Y = Split("肉 菜 蛋 果")
Input #1, N
Line Input #1, R
X = Split(R, ", ")
Call ABC("肉菜蛋果", 0, 0)
For i = 0 To List2.ListCount - 2
For j = i + 1 To List2.ListCount - 1
If Val(List2.List(i)) < Val(List2.List(j)) Then
T = List2.List(i)
List2.List(i) = List2.List(j)
List2.List(j) = T
T = List1.List(i)
List1.List(i) = List1.List(j)
List1.List(j) = T
End If
Next j
Next i
For i = 0 To List1.ListCount - 1
Print #2, Trim(List1.List(i) & " " & List2.List(i))
Next i
Close #2
Close #1
End
End Sub
Sub ABC(A, B, C)
If C = N And RE(A) = False Then
List1.AddItem A
List2.AddItem B
Else
For i = 0 To 3
D = "(" & Y(i) & ")"
If InStr(A, D) = 0 Then Call ABC(Replace(A, Y(i), D), B + X(i), C + 1)
Next i
End If
End Sub
Function RE(A)
P = False
For i = 0 To List1.ListCount - 1
If List1.List(i) = A Then P = True
Next i
RE = P
End Function
Dim s, k
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
Line Input #1, m
s = Split(m, ", ")
k = Split("肉 菜 蛋 果")
Call A1("", n)
Call A3
Close
Close
End
End Sub
Sub A1(a, b)
If Len(a) = b Then
Call A2(a)
Else
For i = 0 To 3
If InStr(a, k(i)) = 0 Then Call A1(a & k(i), b)
Next
End If
End Sub
Sub A2(a)
ans = "肉菜蛋果"
pp = 0
For i = 1 To 2
mm = Mid(a, i, 1)
ans = Replace(ans, mm, "(" & mm & ")")
kk = InStr("肉菜蛋果", mm)
pp = pp + s(kk - 1)
Next
Dim ch As Boolean
For i = 0 To List1.ListCount - 1
If ans = List1.List(i) Then ch = True
Next
If ch = False Then List1.AddItem ans: List2.AddItem pp
End Sub
Sub A3()
For i = 0 To List1.ListCount - 1
For j = 0 To List1.ListCount - 1
If List2.List(j) < List2.List(j - 1) Then
tmp = List2.List(j)
List2.List(j) = List2.List(j - 1)
List2.List(j - 1) = tmp
tmp2 = List1.List(j)
List1.List(j) = List1.List(j - 1)
List1.List(j - 1) = tmp2
End If
Next
Next
For i = List1.ListCount - 1 To 0 Step -1
Print #2, List1.List(i) & " " & List2.List(i)
Next
End Sub