以下是判断prim最小生成树分支节点的C++代码:

int minKey(int key[], bool mstSet[], int V) {
    int min = INT_MAX, min_index;
    for (int v = 0; v < V; v++) {
        if (mstSet[v] == false && key[v] < min) {
            min = key[v];
            min_index = v;
        }
    }
    return min_index;
}

void printMST(int parent[], int **graph, int V) {
    cout<<"Edge \tWeight\n";
    for (int i = 1; i < V; i++)
        cout<<parent[i]<<" - "<<i<<" \t"<<graph[i][parent[i]]<<" \n";
}

void primMST(int **graph, int V) {
    int parent[V]; // to store constructed MST
    int key[V]; // key values used to pick minimum weight edge in cut
    bool mstSet[V]; // to represent set of vertices not yet included in MST
    for (int i = 0; i < V; i++) {
        key[i] = INT_MAX;
        mstSet[i] = false;
    }
    key[0] = 0; // always include first vertex in MST
    parent[0] = -1; // first node is root of MST
    for (int count = 0; count < V-1; count++) {
        int u = minKey(key, mstSet, V); // pick the minimum key vertex from the set of vertices not yet included in MST
        mstSet[u] = true; // add the picked vertex to the MST Set
        for (int v = 0; v < V; v++) {
            if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) {
                parent[v] = u;
                key[v] = graph[u][v];
            }
        }
    }
    printMST(parent, graph, V); // print the constructed MST
}

其中,minKey函数用于从未包含在MST中的顶点中选择最小的key值,printMST函数用于打印生成的MST,primMST函数是Prim算法的主要实现

判断prim最小生成树分支节点的c++代码

原文地址: https://www.cveoy.top/t/topic/fnzA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录