以下代码的复杂度是多少?是 O(n^3log(n)) 吗?
#G is an undirected dense graph, which has N vertices.
import networkx as nx
def cal_minimax_path_matrix(G):
MST = nx.minimum_spanning_tree(G)
minimax_matrix = np.zeros((N, N))
for i in range(N):
for j in range(N):
if j > i:
max_weight = -1
path = nx.shortest_path(MST, source=i, target=j)
for k in range(len(path)-1):
if( MST.edges[path[k],path[k+1]]['weight'] > max_weight):
max_weight = MST.edges[path[k],path[k+1]]['weight']
minimax_matrix[i,j] = minimax_matrix[j,i] = max_weight
return minimax_matrix
构建最小生成树的复杂度为 O(n^2)。在最小生成树中查找最短路径的复杂度是多少?是 O(nlog(n)) 吗?
该代码基于 Madhav-99 的代码,请参阅:
这是添加了关于 O 中每个部分的复杂性的注释的代码:
假设的复杂度
MST = nx.minimum_spanning_tree(G)
为O(n²)。现在增加循环的复杂性:
现在我们面临三个复杂情况:
由于 O(n³ log n) > O(n²)(读取:O(n³ log n) 大于 O(n²)),cal_minimax_path_matrix(n) 的整体复杂度为 O(n³ log n)。
参考文献:
[1] https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html
[2] https://stackoverflow.com/a/26548129/8517948
[3] https://math.stackexchange.com/questions/1524709/minimum-spanning-tree-edge-count