简体   繁体   English

图算法的运行时间

[英]Running Time of Graph Algorithms

I am a bit confused on how to determine the running time of graph algorithms . 我对如何确定图算法的运行时间感到困惑。 That is, determining an estimated running time using the number of vertices (n) and the number of edges (m). 即,使用顶点数(n)和边数(m)确定估计的运行时间。 Does someone mind explaining to me where my logic is flawed, and explain how to properly analyze these and find the running times? 有人介意向我解释我的逻辑存在缺陷,并解释如何正确分析这些并找到运行时间吗?

Here is an example graph algorithm: 这是一个示例图算法:

//input: Directed graph G represented by adjacency lists.
Func1(G) {
k = 0;
foreach vertex vi in V(G) do
    foreach directed edge (vi, vj) incident on vi do
    k=k+1; //just some constant time operation
    end
end
return(k);
}

The running time of this graph algorithm is given as O(m+n) in BigO notation. 该图算法的运行时间以BigO表示法给出为O(m + n)。 Now here is my question: 现在这是我的问题:

Just looking at this algorithm for a quick mental analysis, why isn't the running time instead equal to O(n*m)? 只是看一下这个算法进行快速心理分析,为什么运行时间不等于O(n * m)? The outer loop runs n times, in other words once for each vertex. 外循环运行n次,换句话说,每个顶点运行一次。 Now the inner loop runs once for each edge, m times. 现在内部循环对每个边缘运行一次,m次。 Thus I thought that both loops together would run n*m times. 因此我认为两个循环一起运行n * m次。

One last less trivial question is, how would the algorithm running time change should the input be given as an adjacency matrix, rather than an adjacency list? 最后一个不太重要的问题是,如果输入作为邻接矩阵而不是邻接列表,算法运行时间如何变化?

I cannot find a good resource for this online, there are no clear and concise examples covering this topic. 我无法在网上找到一个好的资源,没有明确和简洁的例子涵盖这个主题。 Would really appreciate if someone can help me create one :) 真的很感激,如果有人可以帮我创建一个:)

It runs once for every edge incident to vi. 它为vi的每个边缘事件运行一次。 As each edge is incident to 2 vertices, in the end, each edge is visited twice, and each vertex once. 当每个边缘入射到2个顶点时,最后,每个边缘被访问两次,每个顶点被访问一次。 So O(n+2m) = O(n+m) using an adjacency list. 所以O(n + 2m)= O(n + m)使用邻接表。

Using an adjacency matrix, to find out which edges are incident to vi, you would need O(n) operations. 使用邻接矩阵,找出哪些边缘入射到vi,您将需要O(n)运算。 So the algorithm would be O(n²). 所以算法是O(n²)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM