prim+优先队列模板:
1 #include<stdio.h> //大概要这些头文件
2 #include<string.h>
3 #include<queue>
4 #include<vector>
5 #include<algorithm>
6 using namespace std;
7 typedef pair<int,int> pii;
8
9 int head[30],next[200],point[200],val[200],size,dist[30]; //前向星及dist数组
10 bool vis[30];
11
12 void add (int a,int b, int v){ //加边及去重
13 int i;
14 for(i=head[a];~i;i=next[i]){
15 if(point[i]==b){
16 if(val[i]>v)val[i]=v;
17 return;
18 }
19 }
20 point[size]=b;
21 val[size]=v;
22 next[size]=head[a];
23 head[a]=size++;
24 }
25
26 struct cmp{ //重载小根堆
27 bool operator()(pii a,pii b){
28 return a.first>b.first;
29 }
30 };
31
32 void prim(int s){ //prim函数,传入图中一点
33 int i,ans=0;
34 memset(dist,-1,sizeof(dist));
35 memset(vis,0,sizeof(vis));
36 priority_queue<pii,vector<pii>,cmp>q;
37 for (i=head[s];~i;i=next[i]){
38 dist[point[i]]=val[i];
39 q.push(make_pair(dist[point[i]],point[i]));
40 }
41 dist[s]=0;
42 vis[s]=1;
43 while(!q.empty()){
44 pii u=q.top();
45 q.pop();
46 if(vis[u.second])continue;
47 vis[u.second]=1;
48 ans+=u.first;
49 for(i=head[u.second];~i;i=next[i]){
50 int j=point[i];
51 if(!vis[j]&&(dist[j]>val[i]||dist[j]==-1)){
52 dist[j]=val[i];
53 q.push(make_pair(dist[j],j));
54 }
55 }
56 }
57 printf("%d\n",ans);
58 }