|
本帖最后由 大灰狼1976 于 2023-9-1 21:51 编辑
全部揉进了一个function,3个函数中我最慢。
- Public Function LongestPath(ByVal strTree As String) As String 'Long
- Dim arrTmp, aTmp, arrMain, Dis&, i&, d As Object, c, disTmp&, sTmp$
- Dim longestPnt$, parentPnt$, thisDis&, longestTmp(2), lTmp&
- Set d = CreateObject("scripting.dictionary")
- Dis = 1 '可扩展功能,strTree内可追加每个节点间的非固定距离如:"2;1;3,3;1;2,4;1;5"
- arrTmp = Split(strTree, ";")
- ReDim arrMain(1 To arrTmp(0), 2)
- For i = 1 To UBound(arrTmp)
- aTmp = Split(arrTmp(i), ",")
- arrMain(aTmp(0), 0) = arrMain(aTmp(0), 0) & "," & aTmp(1) & ";" & Dis
- d(aTmp(0)) = d(aTmp(0)) + 1
- arrMain(aTmp(1), 0) = arrMain(aTmp(1), 0) & "," & aTmp(0) & ";" & Dis
- d(aTmp(1)) = d(aTmp(1)) + 1
- Next i
- Retry:
- For Each c In d.keys
- If d(c) = 1 Then
- sTmp = arrMain(c, 0)
- parentPnt = Val(Mid(sTmp, 2))
- thisDis = Split(sTmp, ";")(1)
- If arrMain(c, 1) <> "" Then
- longestPnt = arrMain(c, 1)
- disTmp = arrMain(c, 2) + thisDis
- Else
- longestPnt = c
- disTmp = thisDis
- End If
- If arrMain(parentPnt, 1) = "" Then
- arrMain(parentPnt, 1) = longestPnt
- arrMain(parentPnt, 2) = disTmp
- Else
- If disTmp + arrMain(parentPnt, 2) > longestTmp(2) Then
- longestTmp(0) = arrMain(parentPnt, 1)
- longestTmp(1) = longestPnt
- longestTmp(2) = disTmp + arrMain(parentPnt, 2)
- End If
- If disTmp > arrMain(parentPnt, 2) Then arrMain(parentPnt, 2) = disTmp: arrMain(parentPnt, 1) = longestPnt
- End If
- d(parentPnt) = d(parentPnt) - 1
- d.Remove c
- arrMain(parentPnt, 0) = Replace(arrMain(parentPnt, 0), "," & c & ";" & thisDis, "")
- End If
- Next c
- If d.Count > 1 Then GoTo Retry
- LongestPath = Join(longestTmp, ",")
- End Function
复制代码 |
|