我编写了一个使用 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 )。

这是我的代码:

#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;
}
有帮助吗?

解决方案

您可以使用邻接表来加速您的解决方案(但不适用于密集图),但即使如此,如果没有斐波那契堆,您也无法获得 O(V log V) 。

也许是 克鲁斯卡算法 你会更容易理解。它没有优先级队列,您只需对边数组进行一次排序。基本上是这样的:

  • 将所有边插入数组并按权重排序
  • 迭代排序后的边,对于连接节点 i 和 j 的每条边,检查 i 和 j 是否相连。如果是,则跳过该边,否则将该边添加到 MST 中。

唯一的问题是能够快速判断两个节点是否已连接。为此,您可以使用并查数据结构,如下所示:

int T[MAX_#_OF_NODES]

int getParent(int a)
{
  if (T[a]==-1)return a;
  return T[a]=getParent(T[a]);
}
void Unite(int a,int b)
{
  if (rand()&1)
     T[a]=b;
  else
     T[b]=a;
}

一开始,只需将 T 初始化为全-1,然后每次想要查明节点 A 和 B 是否连接时,只需比较它们的父节点 - 如果它们相同,则它们是连接的(就像这样 getParent(A)==getParent(B))。当您将边插入 MST 时,请确保将并查找更新为 Unite(getParent(A),getParent(B)).

分析很简单,您对边进行排序并使用需要 O(1) 的 UF 进行迭代。所以它是 O(E logE + E ) 等于 O(E log E)。

这就对了 ;-)

其他提示

我之前不需要处理该算法,但是您所实现的与该算法不匹配,如上所解释的 维基百科. 。该算法的工作原理如下。

  1. 但所有顶点都进入队列。氧(V)
  2. 虽然队列不空...氧(V)
    1. 从队列中取出权重最小的边。O(日志(V))
    2. 更新相邻顶点的权重。O(E / V),这是相邻顶点的平均数量。
    3. 重新建立队列结构。O(日志(V))

这给出了

        O(V) + O(V) * (O(log(V)) + O(V/E))
      = O(V) + O(V) * O(log(V)) + O(V) * O(E / V)
      = O(V) + O(V * log(V)) + O(E)
      = O(V * log(V)) + O(E)

正是人们所期望的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top