堆优化版本的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;
}
相关推荐
KoiHeng44 分钟前
部分排序算法的Java模拟实现(复习向,非0基础)
java·算法·排序算法
岁忧7 小时前
(nice!!!)(LeetCode 面试经典 150 题 ) 30. 串联所有单词的子串 (哈希表+字符串+滑动窗口)
java·c++·leetcode·面试·go·散列表
SunkingYang8 小时前
MFC/C++语言怎么比较CString类型最后一个字符
c++·mfc·cstring·子串·最后一个字符·比较
界面开发小八哥8 小时前
MFC扩展库BCGControlBar Pro v36.2新版亮点:可视化设计器升级
c++·mfc·bcg·界面控件·ui开发
R-G-B8 小时前
【15】MFC入门到精通——MFC弹窗提示 MFC关闭对话框 弹窗提示 MFC按键触发 弹窗提示
c++·mfc·mfc弹窗提示·mfc关闭弹窗提示·mfc按键触发 弹窗提示
艾莉丝努力练剑8 小时前
【数据结构与算法】数据结构初阶:详解顺序表和链表(四)——单链表(下)
c语言·开发语言·数据结构·学习·算法·链表
十秒耿直拆包选手8 小时前
Qt:QCustomPlot类介绍
c++·qt·qcustomplot
珊瑚里的鱼8 小时前
第十三讲 | map和set的使用
开发语言·c++·笔记·visualstudio·visual studio
逑之8 小时前
C++笔记1:命名空间,缺省参数,引用等
开发语言·c++·笔记
berlin51518 小时前
c++判断文件或目录是否存在
c++