堆优化版本的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;
}
相关推荐
闻缺陷则喜何志丹3 分钟前
【分块 差分数组 逆元】3655区间乘法查询后的异或 II|2454
c++·算法·leetcode·分块·差分数组·逆元
葛小白113 分钟前
C#进阶12:C#全局路径规划算法_Dijkstra
算法·c#·dijkstra算法
前端小L14 分钟前
图论专题(五):图遍历的“终极考验”——深度「克隆图」
数据结构·算法·深度优先·图论·宽度优先
CoovallyAIHub35 分钟前
超越像素的视觉:亚像素边缘检测原理、方法与实战
深度学习·算法·计算机视觉
CoovallyAIHub37 分钟前
中科大西工大提出RSKT-Seg:精度速度双提升,开放词汇分割不再难
深度学习·算法·计算机视觉
gugugu.37 分钟前
算法:位运算类型题目练习与总结
算法
百***976443 分钟前
【语义分割】12个主流算法架构介绍、数据集推荐、总结、挑战和未来发展
算法·架构
代码不停1 小时前
Java分治算法题目练习(快速/归并排序)
java·数据结构·算法
bubiyoushang8881 小时前
基于MATLAB的马尔科夫链蒙特卡洛(MCMC)模拟实现方法
人工智能·算法·matlab
玖剹2 小时前
穷举 VS 暴搜 VS 深搜 VS 回溯 VS 剪枝
c语言·c++·算法·深度优先·剪枝·深度优先遍历