prim模板
int vis[30]; int n; int map[30][30]; int d[30]; int prim(){ int i,j,mi,v; for(i=0;i<n;i++){ d[i]=map[0][i]; vis[i]=0; } for(i=1;i<=n;i++){ mi=1<<30; for(j=0;j<n;j++){ if(!vis[j] && mi>d[j]){ v=j; mi=d[j]; } } vis[v]=1; for(j=0;j<n;j++) if(!vis[j] && d[j]>map[v][j]) d[j]=map[v][j]; } for(i=1;i<n;i++) d[0]+=d[i]; return d[0]; }
heap优化
http://www.nocow.cn/index.php/Prim%E7%AE%97%E6%B3%95
1 /* 2 二叉堆优化Prim算法 3 Author:YangZX 4 Date:9.11 2011 5 */ 6 #include <iostream> 7 using namespace std; 8 const int MAXV = 10001, MAXE = 100001, INF = (~0u)>>2; 9 struct edge{ 10 int t, w, next; 11 }es[MAXE * 2]; 12 int h[MAXV], cnt, n, m, heap[MAXV], size, pos[MAXV], dist[MAXV]; 13 void addedge(int x, int y, int z) 14 { 15 es[++cnt].t = y; 16 es[cnt].next = h[x]; 17 es[cnt].w = z; 18 h[x] = cnt; 19 } 20 21 void heapup(int k) 22 { 23 while(k > 1){ 24 if(dist[heap[k>>1]] > dist[heap[k]]){ 25 swap(pos[heap[k>>1]], pos[heap[k]]); 26 swap(heap[k>>1], heap[k]); 27 k>>=1; 28 }else 29 break; 30 } 31 } 32 void heapdown(int k) 33 { 34 while((k<<1) <= size){ 35 int j; 36 if((k<<1) == size || dist[heap[(k<<1)]] < dist[heap[(k<<1)+1]]) 37 j = (k<<1); 38 else 39 j = (k<<1) + 1; 40 if(dist[heap[k]] > dist[heap[j]]){ 41 swap(pos[heap[k]], pos[heap[j]]); 42 swap(heap[k], heap[j]); 43 k=j; 44 }else 45 break; 46 } 47 } 48 void push(int v, int d) 49 { 50 dist[v] = d; 51 heap[++size] = v; 52 pos[v] = size; 53 heapup(size); 54 } 55 int pop() 56 { 57 int ret = heap[1]; 58 swap(pos[heap[size]], pos[heap[1]]); 59 swap(heap[size], heap[1]); 60 size--; 61 heapdown(1); 62 return ret; 63 } 64 65 int prim() 66 { 67 int mst = 0, i, p; 68 push(1, 0); 69 for(i=2; i<=n; i++) 70 push(i, INF); 71 for(i=1; i<=n; i++){ 72 int t = pop(); 73 mst += dist[t]; 74 pos[t] = -1; 75 for(p = h[t]; p; p = es[p].next){ 76 int dst = es[p].t; 77 if(pos[dst] != -1 && dist[dst] > es[p].w){ 78 dist[dst] = es[p].w; 79 heapup(pos[dst]); 80 heapdown(pos[dst]); 81 } 82 } 83 } 84 return mst; 85 } 86 int main() 87 { 88 cin>>n>>m; 89 for(int i=1; i<=m; i++){ 90 int x, y, z; 91 cin>>x>>y>>z; 92 addedge(x, y, z); 93 addedge(y, x, z); 94 } 95 cout<<prim()<<endl; 96 return 0; 97 }