prim算法

https://en.wikipedia.org/wiki/Prim%27s_algorithm

 1 int n,m;
 2 struct edgetype
 3 {
 4     int from;
 5     int to;
 6     int len;
 7 };
 8 struct pointtype
 9 {
10     vector<edgetype> next;
11     bool vis;
12 }point[100001];
13 struct com
14 {
15     bool operator ()(edgetype& x,edgetype& y)
16     {
17         return x.len>y.len;
18     }
19 };
20 priority_queue<edgetype,vector<edgetype>,com> heap;
21 void init()
22 {
23     scanf("%d%d",&n,&m);
24     for(int i=1;i<=n;i++)
25     {
26         point[i].next.clear();
27         point[i].vis=false;
28     }
29     for(int i=1;i<=m;i++)
30     {
31         edgetype tmp;
32         scanf("%d%d%d",&tmp.from,&tmp.to,&tmp.len);
33         point[tmp.from].next.push_back(tmp);
34         swap(tmp.from,tmp.to);
35         point[tmp.from].next.push_back(tmp);
36     }
37     vector<edgetype>::iterator it;
38     for(it=point[1].next.begin();it!=point[1].next.end();it++)
39     {
40         heap.push(*it);
41     }
42     point[1].vis=true;
43     return;
44 }
45 int prim()
46 {
47     int res=0;
48     while(!heap.empty())
49     {
50         edgetype now=heap.top();
51         heap.pop();
52         int tip=now.to;
53         if(!point[tip].vis)
54         {
55             point[tip].vis=true;
56             res+=now.len;
57             vector<edgetype>::iterator it;
58             for(it=point[tip].next.begin();it!=point[tip].next.end();it++)
59             {
60                 if(!point[(*it).to].vis)
61                 {
62                     heap.push(*it);
63                 }
64             }
65         }
66     }
67     return res;
68 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值