2016年8月15日 星期一

北二區101-2小三數學(vb版)


參考程式碼:
 
    Const inf As Long = 1.0E+18
    Dim n, m As Long
    Dim s As String
    Function cal(ByVal x As Long, ByVal y As Long, ByVal op As Integer) As Long
' 根據 op 計算兩數之 +-*/
        cal = inf
        If x = inf Or y = inf Then Return inf
        Select Case op
            Case 1 : Return x + y
            Case 2 : Return x - y
            Case 3 : Return x * y
            Case 4
                If y = 0 OrElse x Mod y <> 0 Then
                    Return inf
                Else
                    Return x / y
                End If
        End Select
    End Function
    Function cal3(ByVal x As Long, ByVal y As Long, ByVal z As Long, ByVal op1 As Integer, ByVal op2 As Integer) As Long
' 根據 op1,op2 計算三數之 計算結果
        cal3 = inf
        If op1 \ 3 < op2 \ 3 Then  '1+2- ,3*4/ :若op1為1,2且op2為3,4則先 算op2
            Return cal(x, cal(y, z, op2), op1)
        Else
            Return cal(cal(x, y, op1), z, op2)
        End If
    End Function
    Dim ops As String = "+-*/"
    Sub cut2(ByVal p As Integer) '分成兩個數字 a,b 呼叫 cal算出所有+-*/可能的值
        Dim a, b As Long
        a = Val(Strings.Left(s, p))
        b = Val(Strings.Right(s, n - p))
        ' PrintLine(3, "===" & a & "," & b )  '可列印參考
        For op = 1 To 4
            If cal(a, b, op) = m Then
                PrintLine(3, a & Mid(ops, op, 1) & b)
            End If
        Next
    End Sub
    Sub cut3(ByVal p As Integer, ByVal q As Integer) '分成三 個數字 a,b,c 呼叫 cal3算出所有可能的值
        Dim a, b, c As Long
        a = Val(Strings.Left(s, p))
        b = Val(Mid(s, p + 1, q - p))
        c = Val(Strings.Right(s, n - q))
        ' PrintLine(3, "===" & a & "," & b & "," & c)  '可列印參考
        For op1 = 1 To 4
            For op2 = 1 To 4
                If cal3(a, b, c, op1, op2) = m Then
                    PrintLine(3, a & Mid(ops, op1, 1) & b & Mid(ops, op2, 1) & c)
                End If
            Next op2
        Next op1

    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        FileOpen(1, "in1.txt", OpenMode.Input)
        'FileOpen(2, "in2.txt", OpenMode.Input) '本題 只一個檔
        FileOpen(3, "out.txt", OpenMode.Output)
        For fn = 1 To 1 '本題 只一個檔
            If fn = 2 Then PrintLine(3)
            Dim t As Short = LineInput(fn)
            For k = 1 To t
                n = LineInput(fn)
                s = LineInput(fn)
                m = LineInput(fn)
                For i = 1 To n - 1
                    cut2(i)
                Next i
                For i = 1 To n - 2
                    For j = i + 1 To n - 1
                        cut3(i, j)
                    Next
                Next
            Next k
        Next
        End
    End Sub
in1.txt
7
3
123
4
3
234
14
5
24015
16
3
862
4
2
22
4
10
1357924680
-626963
3
334
5

out.txt
12/3
2+3*4
240/15
8-6+2
2+2
2*2
1357-924*680
3*3-4
3/3+4
說明:
第5組輸入,2+2=4及2*2=4有兩個答案
第7組輸入,3*3-4=5及3/3+4=5有兩個答案

0 意見:

張貼留言