Problem 4 (借盤子 13%)
張三把所持有的1000個盤子分別裝在10個箱子裡,每個箱子分別裝進1、2、4、8、16、32、64、128、256、及489個盤子。張三將這些箱子依序標上1~10的號碼。有天,李四想找張三借N個盤子,張三知道每個箱子的編號與箱子內所放盤子的個數,但如何設計一個程式,在不拆開箱子重新組合盤子的情況下,告訴張三應拿出那些箱子給李四,才能得到李四要借的盤子數目呢?
輸入說明:每列中的數字代表要借的盤子數,當為0時表示結束。(請參照輸入範例)
輸入範圍:每列中的數字皆大於0,小於等於1000。
輸入範例:test4.txt
717
329
0
第 3 頁/共 5 頁
輸出說明:每個數字代表箱子的編號,每個數字與數字間的區隔為一個空白符號,請由大到小排列。(請參照輸出範例)
輸出範例:result4.txt
10 8 7 6 3
9 7 4 1
Dim s
回覆刪除Private Sub Form_Load()
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
s = Split("X 1 2 4 8 16 32 64 128 256 489")
Do While Not EOF(1)
Input #1, n
If n <> 0 Then
Call A1("", n, "")
End If
Loop
Close
Close
End Sub
Sub A1(a, b, c)
Dim m, sum As Integer
sum = 0
m = Split(a)
For i = 0 To UBound(m): sum = sum + Val(m(i)): Next
If sum = b Then Print #2, c: Exit Sub
For i = 1 To 10
If Instr2(a, s(i)) = 0 Then Call A1(s(i) & " " & a, b, c & " " & i)
Next
End Sub
Function Instr2(a, b)
Dim AA
AA = Split(a)
Instr2 = 0
For i = 0 To UBound(AA)
If b = AA(i) Then Instr2 = 1
Next
End Function
這要跑很久 10^10 估計要跑5分鐘
Dim s
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
s = Split("X 1 2 4 8 16 32 64 128 256 489")
Do While Not EOF(1)
Input #1, n
If n <> 0 Then
Call A1(n)
End If
Loop
Close
Close
End
End Sub
Sub A1(ByVal a)
Dim X
X = ""
For i = 10 To 1 Step -1
If a - s(i) >= 0 Then a = a - s(i): X = X & " " & i
Next
Print #2, X
End Sub
應該是這樣才對
Dim A(10) As Integer
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
For i = 1 To 9
A(i) = 2 ^ (i - 1)
Next i
A(10) = 489
Do While Not EOF(1)
Input #1, x
If x = 0 Then Exit Do
ans = ""
For i = 10 To 1 Step -1
If x >= A(i) Then x = x - A(i): ans = ans & " " & i
Next i
Print #2, ans
Loop
Close #2
Close #1
End
End Sub
Sub main()
回覆刪除Open App.Path & "\test4.txt" For Input As #1
Open App.Path & "\result4.txt" For Output As #2
tmp = Array(1, 2, 4, 8, 16, 32, 64, 128, 256, 489)
Do Until EOF(1)
Line Input #1, a
If a = 0 Then Exit Do
For i = 9 To 0 Step -1
If Val(a) >= tmp(i) Then
a = Val(a) - tmp(i)
out = out & Str(i + 1)
End If
Next
Print #2, LTrim(out)
out = ""
Loop
End Sub