舉例,由圖 2-1這個樹狀圖來說,「節點 a」是樹根。另外,「節點 d」、「節點 e」和「節點 g」三者是樹葉,因為它們都沒有「兒子」節點。從樹根到「節點 d」至少要經過 2個「邊」;到「節點 e」至少要經過 2個「邊」;到「節點 g」至少要經過 3個「邊」。
輸入說明:第 1行表示樹狀圖共有多少個節點(節點總數不超過 100個),第 2行起每行包括
1個節點資料。每行的節點資料包括 2個符號,以逗號隔開:第 1個符號為「節點名稱」,第
2個符號為其「父親名稱」。若是「樹根」節點,其父親表示為「---」3個連續減號。
輸出說明:輸出所有「樹葉」節點,並輸出從「樹根」到該「樹葉」至少需經過的「邊」的個數。每行輸出 1組「樹葉」及「至少經過的『邊』的個數」資料,其間以空白隔開,各「樹葉」節點輸出之順序不限。
輸入檔案 1:【檔名:in1.txt】11
A, ---
B, A
C, A
D, B
E, B
F, C
G, E
H, G
I, G
J, I
K, I
輸入檔案 2:【檔名:in2.txt】
12
A, ---
B, A
C, A
D, A
E, B
F, B
G, C
H, C
I, D
J, D
K, E
L, E
D 2
H 4
J 5
K 5
F 2
K 3
L 3
F 2
G 2
H 2
I 2
J 2
Private Sub Form_Load()
回覆刪除Me.Hide
Open App.Path & "\in1.txt" For Input As #1
Open App.Path & "\in2.txt" For Input As #2
Open App.Path & "\out.txt" For Output As #3
'----------------in1.txt--------------------
Input #1, N
For ii = 1 To N
Line Input #1, X
Y = Split(X, ", ")
List1.AddItem Y(0)
List2.AddItem Y(1)
Next ii
If List2.List(0) = "---" Then List3.AddItem List1.List(0)
For i = 1 To List2.ListCount - 1
Call Find(List2.List(i), i)
Next i
For i = 1 To List2.ListCount - 1
Call Del(List2.List(i))
Next i
For i = 0 To List3.ListCount - 1
Z = Split(List3.List(i))
Print #3, Z(UBound(Z)) & " " & UBound(Z)
Next i
'----------------RE-------------------------
List1.Clear: List2.Clear: List3.Clear
Print #3,
'----------------in2.txt--------------------
Input #2, N
For ii = 1 To N
Line Input #2, X
Y = Split(X, ", ")
List1.AddItem Y(0)
List2.AddItem Y(1)
Next ii
If List2.List(0) = "---" Then List3.AddItem List1.List(0)
For i = 1 To List2.ListCount - 1
Call Find(List2.List(i), i)
Next i
For i = 1 To List2.ListCount - 1
Call Del(List2.List(i))
Next i
For i = 0 To List3.ListCount - 1
Z = Split(List3.List(i))
Print #3, Z(UBound(Z)) & " " & UBound(Z)
Next i
Close #3
Close #2
Close #1
End
End Sub
Sub Find(A, B)
For i = 0 To List3.ListCount - 1
Z = Split(List3.List(i))
If A = Z(UBound(Z)) Then List3.AddItem List3.List(i) & " " & List1.List(B)
Next i
End Sub
Sub Del(A)
For i = 0 To List3.ListCount - 1
If Len(List3.List(i)) >= 1 Then
Z = Split(List3.List(i))
If A = Z(UBound(Z)) Then List3.RemoveItem (i)
End If
Next i
End Sub
---------out.txt
D 2
F 2
H 4
J 5
K 5
F 2
G 2
H 2
I 2
J 2
K 3
L 3
Dim k
回覆刪除Private Sub Form_Load()
Me.Hide
Open App.Path & "\in1.txt" For Input As #1
Open App.Path & "\in2.txt" For Input As #2
Open App.Path & "\out.txt" For Output As #3
'------------------
Input #1, t
For i = 1 To t
Input #1, m, n
Call A1(m, n)
Next
Call A2
'------------------
Print #3, " "
List1.Clear
'------------------
Input #2, t
For i = 1 To t
Input #2, m, n
Call A1(m, n)
Next
Call A2
'------------------
Close
Close
Close
End
End Sub
Sub A1(m, n)
If n <> "---" Then
For i = 0 To List1.ListCount - 1
If n = Right(List1.List(i), 1) Then tmp = List1.List(i): List1.List(i) = tmp: List1.AddItem tmp & m: k = k & n
Next
Else
List1.AddItem m
End If
End Sub
Sub A2()
For i = 0 To List1.ListCount - 1
op = Right(List1.List(i), 1)
If InStr(k, op) = 0 Then Print #3, op & " " & (Len(List1.List(i)) - 1)
Next
End Sub