106_Prime 最小生成树

  最小生成树的Prime算法,用优先队列来实现。

 《挑战程序竞赛》中, 使用一个min_cost数组来保存最小生成树倒每个结点的最短距离,每次操作对V进行循环;

  对比了一下,以下程序,基于与最小生成树相连的边的优先队列,分析了一下不一定能占到便宜。


//
//  106_Prime.cpp
//  changlle
//
//  Created by user on 1/1/16.
//  Copyright (c) 2016 user. All rights reserved.
//

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int min_cost=0;
struct edge {
    int cost;
    int to;
};
vector<edge> G[4];

bool used[4];

typedef pair<int,int> P;

int V=4;




int main() {
    edge e={1,1};
    G[0].push_back(e);
    e={4,3};
    G[0].push_back(e);
    
    e={2,2};
    G[1].push_back(e);
    e={5,3};
    G[1].push_back(e);
    e={1,0};
    G[1].push_back(e);
    
    
    e={3,3};
    G[2].push_back(e);
    e={2,1};
    G[2].push_back(e);
    
    e={4,0};
    G[3].push_back(e);
    e={3,2};
    G[3].push_back(e);
    e={5,1};
    G[3].push_back(e);
    
    
    
   
    priority_queue<P, vector<P>, greater<P>> que;
    
    for (int i=0; i<G[0].size();i++)
    {
        P e;
        e.first=G[0][i].cost;
        e.second=G[0][i].to;
        que.push(e);
    }
    
    int n=1;
    fill (used, used+V, false);
    used[0]=true;
    
    while (n<V) {
        
        P e=que.top(); que.pop();
        min_cost=min_cost+e.first;
        n++;
        used[e.second]=true;
        int now=e.second;
        
        for (int j=0; j<G[now].size();j++)
        {
            if (!used[G[now][j].to]){
                P e_1;
                e_1.first=G[now][j].cost;
                e_1.second=G[now][j].to;
                que.push(e_1);
            }
        }
        
        
    }
    
    
    
    
    cout<<min_cost<<endl;
    
    
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值