Day7 prim的堆优化

题目链接:点击打开链接

复杂度:O(MlogM) (M为边数),未优化时复杂度为O(N^2)

首先把1这个点标记为已访问,把它所连的边都加到优先队列里边,然后每次从优先队列顶端拿终点未访问的边,把终点标记成已访问,把终点连的边放进优先队列,直到无边可拿或所有点均访问过为止。

代码:参考别人的代码..    https://blog.csdn.net/jhgkjhg_ugtdk77/article/details/47081375

#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
const int maxn = 1000005;

struct Edge{
    int from,to,len;
    Edge(int x,int y,int l){
        this -> from = x;
        this -> to = y;
        this -> len = l;
    }
    friend bool operator<(Edge a,Edge b){
        return a.len>b.len;
    }
};

priority_queue<Edge> pq;
vector<Edge> graph[maxn];
bool vis[maxn];

int n,m;

int main(){
    scanf("%d%d",&n,&m);
    int x,y,l;
    for(int i=1; i<=m; i++){
        scanf("%d%d%d",&x,&y,&l);
        graph[x].push_back(Edge(x,y,l));
        graph[y].push_back(Edge(y,x,l));
    }

    while(!pq.empty()) pq.pop();
    for(int i=0; i<graph[1].size(); i++){
        pq.push(graph[1][i]);
    }
    vis[1] = true;
    int left = n;
    int ans = 0;
    while((!pq.empty()) && left){
        Edge e = pq.top(); pq.pop();
        if(vis[e.to]) continue;
        ans += e.len;
        left --;
        vis[e.to] = true;
        for(int i=0; i<graph[e.to].size(); i++){
            Edge ee = graph[e.to][i];
            if(vis[ee.to] == false){
                pq.push(ee);
            }
        }
    }
    printf("%d\n",ans);

    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值