堆优化的prim算法

《挑战程序设计竞赛》中对最小生成树中的prim算法只给出了未优化形式,而对于堆优化,只是简单地分析了时间复杂度,而对于堆优化问题,网上的答案不多,因此手写一份堆优化代码模板(理解后可直接使用)
 //maxV是顶点最大数
typedef pair<int, int>P;
struct Edge
{
    int to, cost;
};
vector<Edge>edge[maxV];
int V;
int mincost[maxV];
bool vis[maxV];
void prim()
{
    priority_queue<P, vector<P>, greater<P> >que;
    fill(mincost, mincost + V, inf);
    memset(vis, false, sizeof(vis));
    int ans = 0;
    mincost[0] = 0;
    que.push(P(0, 0));
    while(!que.empty())
    {
        P p = que.top();
        que.pop();
        int v = p.second;
        vis[v] = true;
        if(mincost[v] < p.first)
            continue;
        for(int i = 0; i < edge[v].size(); i++)
        {
            Edge e = edge[v][i];
            if(!vis[e.to] && mincost[e.to] > e.cost)
            {
                ans += e.cost;
                if(mincost[e.to] != inf)
                    ans -= mincost[e.to];
                mincost[e.to] = e.cost;
                que.push(P(mincost[e.to], e.to));
            }
        }
    }
    printf("%d\n", ans);
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值