|
本帖最后由 Moneky 于 2014-11-20 23:39 编辑
先扔一块砖。
无脑穷举法,基本上3分钟内可以求出(用附件中的代码生成的数据),没有仔细看过数据,但怎么最长的才几十这个数量级,难道一个节点有N多个儿子?
- Public Function LongestPath(ByVal strTree As String) As Long
- ' Dim s As String
- Dim arr, brr
- Dim i As Long, j As Long, t As Long, lCount As Long, N() As Long
- Dim maxI As Long, maxJ As Long, maxC As Long
- Dim d As New Dictionary
- LongestPath = 1
- ' s = "8;1,2;1,3;2,4;2,6;3,5;5,7;5,8"
- ' arr = Split(s, ";")
- arr = Split(strTree, ";")
- lCount = CLng(arr(0))
- ReDim N(1 To lCount)
- For i = 1 To UBound(arr)
- brr = Split(arr(i), ",")
- N(CLng(brr(1))) = CLng(brr(0))
- Next
- For i = 2 To lCount - 1
- For j = i + 1 To lCount
- t = N(j): c = 0
- If t = i Then c = 1: GoTo V_END
- Do
- c = c + 1
- d(t) = c
- t = N(t)
- If t = i Then c = c + 1: GoTo V_END1
- Loop Until t = 0
- t = N(i): c = 1
- If t = j Then c = 1: GoTo V_END1
- Do
- If d(t) > 0 Then
- c = c + d(t)
- GoTo V_END1
- Else
- c = c + 1
- d(t) = c
- t = N(t)
- If t = j Then c = c + 1: GoTo V_END1
- End If
- Loop Until t = 0
- V_END1:
- d.RemoveAll
-
- V_END:
- Debug.Print i, j, c
- If c > LongestPath Then LongestPath = c ': maxI = i: maxJ = j
- Next
- Next
- End Function
复制代码
晕,原来没有考虑到下面点评中的情况,直接剔除了1号节点了。当然代码改改还是比较容易的,只需改成:- Public Function LongestPath(ByVal strTree As String) As Long
- ' Dim s As String
- Dim arr, brr
- Dim i As Long, j As Long, t As Long, lCount As Long, n() As Long
- ' Dim maxI As Long, maxJ As Long, maxC As Long
- Dim d As New Dictionary
- LongestPath = 1
- ' s = "8;1,2;1,3;2,4;2,6;3,5;5,7;5,8"
- ' arr = Split(s, ";")
- arr = Split(strTree, ";")
- lCount = CLng(arr(0))
- ReDim n(1 To lCount)
- For i = 1 To UBound(arr)
- brr = Split(arr(i), ",")
- n(CLng(brr(1))) = CLng(brr(0))
- Next
- For i = 1 To lCount - 1 '其实就只是把这一句的2改成了1
- For j = i + 1 To lCount
- t = n(j): c = 0
- If t = i Then c = 1: GoTo V_END
- Do
- c = c + 1
- d(t) = c
- t = n(t)
- If t = i Then c = c + 1: GoTo V_END1
- Loop Until t = 0
- t = n(i): c = 1
- If t = j Then c = 1: GoTo V_END1
- Do
- If d(t) > 0 Then
- c = c + d(t)
- GoTo V_END1
- Else
- c = c + 1
- d(t) = c
- t = n(t)
- If t = j Then c = c + 1: GoTo V_END1
- End If
- Loop Until t = 0
- V_END1:
- d.RemoveAll
-
- V_END:
- ' Debug.Print i, j, c
- If c > LongestPath Then LongestPath = c ': maxI = i: maxJ = j
- Next
- Next
- End Function
复制代码
|
评分
-
1
查看全部评分
-
|