c++ - prims 算法中父数组始终为零

标签 c++ prims-algorithm

我有以下函数来查找父数组,以便使用 Prim 算法获得图的最小生成树。

#include<stdlib.h> 
#include <limits.h>
#include <iostream>

int printMST(int parent[], int n, int** graph)
{
for (int i = 1; i < n; i++)
std::cout<<parent[i]<<" - "<<i<<" "<<graph[i][parent[i]]<<"\n";
}
int* prim(int** graph,int no_of_vertices);
int main(){
int no_of_vertices;
std::cin>>no_of_vertices;
int** graph = new int*[no_of_vertices];
for(int i = 0; i < no_of_vertices; ++i)
 graph[i] = new int[no_of_vertices];
for(int i = 0; i <no_of_vertices; ++i)
for(int j = 0; j < no_of_vertices; ++j)
  std::cin>>graph[i][j];

 int* parent;
parent= prim(graph,no_of_vertices);
// Print the solution
printMST(parent, no_of_vertices, graph);
 return 0;
}

int nodeWithMinKey(int key[],bool mst[], int no_of_vertices)
{
int min=1000,min_index;

for(int i=0;i<no_of_vertices;i++)
{
if(mst[i]=false && key[i]<min)
    {
    min=key[i];
    min_index=i;
    }

}

return min_index;
}
int* prim(int** graph, int no_of_vertices){
    int* parent = (int*)malloc(sizeof(int)*no_of_vertices);

    int key[100];
    bool mst[100];
    int i;

    for(i = 0; i<no_of_vertices; i++)
    {
        key[i] = 1000;
        mst[i] = false;
    }

    key[0] = 0;
    parent[0] = -1;

    for(i = 0; i<no_of_vertices-1; i++)
    {
        int u = nodeWithMinKey(key, mst, no_of_vertices);

        mst[u] = true;

        for(int v = 0; v<no_of_vertices; v++)
        {
            if(graph[u][v] && mst[v] == false && graph[u][v] <  key[v])
            {
                parent[v] = u;
                key[v] = graph[u][v];
            }

        }
    }
    return parent;
}

但是父数组的所有值都是“0”(零),不知道哪里出了问题。

最佳答案

这一行

if(mst[i]=false && key[i]<min)

有一个赋值=而不是比较==。这将始终导致 if 测试始终失败,因此您的 min_index 将永远不会被设置。

关于c++ - prims 算法中父数组始终为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30796073/

相关文章:

algorithm - Kruskal 和 Prim 算法的应用

c++ - 尝试将 User32.lib 添加到链接器而不是使用 #pragma 注释(lib, "User32.lib")

c++ - 关于 std::stack push 段错误的问题

c - 以邻接矩阵作为参数的 Prim MST

algorithm - 如何用斐波那契堆实现 Prim 算法?

algorithm - Prim 和 Dijkstra 算法的区别?

algorithm - Prim 算法和 Dijkstra 算法之间的区别?

c++ - gcc arm 中的 strncpy 替换

c++ - 从基类指针 C++ 访问子类成员

c++ - GCC w/inline assembly & -Ofast 为内存操作数生成额外代码