我已经编写了一段代码,使用Prim方法解决MST问题。我读到这种实现方式(使用优先队列)应该具有O(E + VlogV) = O(VlogV)的时间复杂度,其中E是边的数量,V是点的数量,但是当我看我的代码时,它似乎并不是这样。如果有人能为我解释一下,我将不胜感激。
在我看来,运行时间如下: while循环需要O(E)次(直到我们遍历完所有的边) 在该循环内部,我们从Q中提取一个元素,需要O(logE)的时间。 第二个内部循环需要O(V)的时间(虽然我们不总是运行此循环,但显然它将被运行V次,因为我们必须添加所有的顶点)
我的结论是,运行时间为:O( E(logE+V) ) = O( E*V )。
这是我的代码:
在我看来,运行时间如下: while循环需要O(E)次(直到我们遍历完所有的边) 在该循环内部,我们从Q中提取一个元素,需要O(logE)的时间。 第二个内部循环需要O(V)的时间(虽然我们不总是运行此循环,但显然它将被运行V次,因为我们必须添加所有的顶点)
我的结论是,运行时间为:O( E(logE+V) ) = O( E*V )。
这是我的代码:
#define p_int pair < int, int >
int N, M; //N - nmb of vertices, M - nmb of edges
int graph[100][100] = { 0 }; //adj. matrix
bool in_tree[100] = { false }; //if a node if in the mst
priority_queue< p_int, vector < p_int >, greater < p_int > > Q;
/*
keeps track of what is the smallest edge connecting a node in the mst tree and
a node outside the tree. First part of pair is the weight of the edge and the
second is the node. We dont remember the parent node beaceuse we dont need it :-)
*/
int mst_prim()
{
Q.push( make_pair( 0, 0 ) );
int nconnected = 0;
int mst_cost = 0;
while( nconnected < N )
{
p_int node = Q.top(); Q.pop();
if( in_tree[ node.second ] == false )
{
mst_cost += node.first;
in_tree[ node.second ] = true;
for( int i = 0; i < N; ++i )
if( graph[ node.second ][i] > 0 && in_tree[i]== false )
Q.push( make_pair( graph[ node.second ][i], i ) );
nconnected++;
}
}
return mst_cost;
}