Prim最小生成树算法


MST-PRIM(G, w, r)
// G: graph, w: weight,  r:root 
1  for each u V [G]
 2       do key[u]  
  
  
 3          π[u]  NIL
  
  
 4  key[r]  0
  
  
 5   Q  V [G]
  
  
 6   while Q  Ø
  
  
 7       do u  EXTRACT-MIN(Q)
  
  
 8          for each v  Adj[u]
  
  
 9              do if v  Q and w(u, v) < key[v]
  
  
10                    then π[v]  u
  
  
11                         key[v]  w(u, v)

Prim's algorithm works as shown in the figure:
https://p-blog.csdn.net/images/p_blog_csdn_net/touzani/303255/o_prim.JPG
//  MST  set实现最小优先级队列
#include  < vector >
#include 
< set >

int  MST_PRIM( const  vector < vector < pair < int int >   >   >   &  G)
/*
  • index start from 1 to n and
  • G.size() -1 is the number of vertices in our graph
  • G[i].size() is the number of vertices directly reachable from vertex with index i
  • G[i][j].first is the index of j-th vertex reachable from vertex i
  • G[i][j].second is the length of the edge heading from vertex i to vertex G[i][j].first 
         return the minimum cost of the spanning tree
*/
{
    
int n = G.size();
    vector
<int> key (n, 987654321);
    vector
<bool> belongQ(n, 1);
    key[
1]=0;
    
set<pair<intint> > Q;
    
for(int i=1; i<n; i++
        Q.insert(make_pair(key[i], i));
    
while (!Q.empty()) {
        
int u=Q.begin()->second;
        Q.erase(Q.begin());
        belongQ[u]
=false;
        
for(int i=0; i< G[u].size(); i++{
            
int v = G[u][i].first;
            
if(belongQ[v] && G[u][i].second < key[v]) {
                Q.erase(Q.find(make_pair(key[v], v)));
                key[v]
=G[u][i].second;
                Q.insert(make_pair(key[v], v));
            }

        }

    }
 
    
int res=0;
    
for(int i=1; i < n; i++
        res
+=key[i];
    
return res;
}
 
题目:http://acm.pku.cn/JudgeOnline/problem?id=1251 jungle roads   
            http://acm.pku.cn/JudgeOnline/problem?id=1287 Networking

width="728" scrolling="no" height="90" frameborder="0" align="middle" src="http://download1.csdn.net/down3/20070601/01184120111.htm" marginheight="0" marginwidth="0">
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值