堆优化版本的Prim

  • prim和dijkstra每轮找最小边的松弛操作其实是同源的,因而受dijkstra堆优化的启发,那么prim也可以采用小根堆进行优化。
  • 时间复杂度也由 O ( n 2 ) O(n^2) O(n2)降为 O ( n l o g n ) O(nlogn) O(nlogn)。

测试一下吧:原题链接

cpp 复制代码
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
typedef int VertexType;
typedef int Info;
typedef pair<int,int> PII;

const int N = 110;

// 书面形式的邻接表
typedef struct ArcNode{
    int adjvex;
    Info weight;
    struct ArcNode* nextarc;
}ArcNode;
typedef struct VNode{
    VertexType data;        // 这里  结点编号就是结点表的下标  一一映射
    ArcNode* firstarc;
}VNode, AdjList[N];
typedef struct ALGraph{
    AdjList vertices;
    int vexnum, arcnum;
    ALGraph(){for(int i = 0;i < N;i ++)         vertices[i].firstarc = nullptr;}
}ALGraph;

int prim_with_heap(ALGraph& G){
    int sum = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    int dist[N];
    bool st[N];
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    
    dist[1] = 0;
    heap.push({0, 1});
    while(heap.size()){
        PII t = heap.top();
        heap.pop();
        int vex = t.second, distance = t.first;
        if(st[vex])     continue;
        st[vex] = true;
        sum += distance;
        for(ArcNode* parc = G.vertices[vex].firstarc;parc;parc = parc -> nextarc)
            if((parc -> weight) < dist[parc -> adjvex]){
                dist[parc -> adjvex] = parc -> weight;
                heap.push({parc -> weight, parc -> adjvex});
            }
    }
    return sum;
}

void add(ALGraph& G, VertexType a, VertexType b, Info w){   // a -> b
    VNode* u = &G.vertices[a];
    ArcNode* newarc = new ArcNode;
    newarc -> adjvex = b;
    newarc -> weight = w;
    newarc -> nextarc = u -> firstarc;
    u -> firstarc = newarc;     // 头插法
    G.arcnum ++;
}

int main(){
    ALGraph g;
    cin >> g.vexnum;
    for(int i = 1;i <= g.vexnum;i ++)
        for(int j = 1;j <= g.vexnum;j ++){
            int w;
            cin >> w;
            add(g, i, j, w);
        }
    int sum = prim_with_heap(g);
    cout << sum << endl;
    return 0;
}
相关推荐
无限进步_5 分钟前
【C++】巧用静态变量与构造函数:一种非常规的求和实现
开发语言·c++·git·算法·leetcode·github·visual studio
小超超爱学习993722 分钟前
大数乘法,超级简单模板
开发语言·c++·算法
Ricardo-Yang36 分钟前
SCNP语义分割边缘logits策略
数据结构·人工智能·python·深度学习·算法
凌波粒37 分钟前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼1 小时前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
soragui1 小时前
【Python】第 4 章:Python 数据结构实现
数据结构·windows·python
sinat_286945191 小时前
harness engineering
人工智能·算法·chatgpt
少许极端2 小时前
算法奇妙屋(四十三)-贪心算法学习之路10
学习·算法·贪心算法
samroom2 小时前
【鸿蒙应用开发 Dev ECO Studio 5.0版本】从0到1!从无到有!最全!计算器------按钮动画、滑动退格、中缀表达式转后缀表达式、UI设计
数据结构·ui·华为·typescript·harmonyos·鸿蒙
xyx-3v2 小时前
qt创建新工程
开发语言·c++·qt