Problem 2 (總和檢查 16%)
請檢查一個數列中,尋找任兩個數字相加後的和是否會等於輸入的檢查值。例如,有一個數列為8,20,27,17,13,28,35,31,若輸入的檢查值為48,會找到20及28兩個數,相加的和為48;反之若輸入的檢查值為50,則會找不到配對的數字。
輸入說明:輸入之第一列為下一列數列中的個數,第二為列為數列資料。每個數字與數字間的區隔為一個空白符號。第三列及以後的資料為輸入的檢查值,每一列有一個檢查值,當為0時表示結束。(請參照輸入範例)
第 1 頁/共 5 頁
輸入範圍:輸入的數列最少有2個數字,最多不超過100個。每個數列中的數字皆大於0,小於1000,且不重覆。
輸入範例:test2.txt
8
8 20 27 17 13 28 35 31
48
50
0
輸出說明:每個檢查值有一個輸出結果,若有匹配的檢查值,則輸出為1,反之為-1。(請參照輸出範例)
輸出範例:result2.txt
1
-1
Dim s, ans
回覆刪除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, t
Line Input #1, m
s = Split(m)
Do While Not EOF(1)
Input #1, n
If n <> 0 Then
ans = -1
Call a1(n, "", 0)
Print #2, ans
End If
Loop
Close
Close
End
End Sub
Sub a1(a, b, c)
If c = 2 Then
Dim QQ
QQ = Split(b)
If Val(QQ(0)) + Val(QQ(1)) = a Then ans = 1
Else
For i = 0 To UBound(s)
If Instr2(b, s(i)) = 0 Then Call a1(a, s(i) & " " & b, c + 1)
Next
End If
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
Dim X()
回覆刪除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
ReDim X(N)
For i = 1 To N
Input #1, X(i)
Next i
Do While Not EOF(1)
Input #1, A
If A = 0 Then Exit Do
P = False
For i = 1 To (N - 1)
For j = i + 1 To N
If X(i) + X(j) = A Then P = True
Next j
Next i
If P = True Then Print #2, 1 Else Print #2, -1
Loop
Close #2
Close #1
End
End Sub