int vis[];
int n;
int map[][];
int d[];
int prim(){
int i,j,mi,v;
for(i=;i<n;i++){
d[i]=map[][i];
vis[i]=;
}
for(i=;i<=n;i++){
mi=<<;
for(j=;j<n;j++){
if(!vis[j] && mi>d[j]){
v=j;
mi=d[j];
}
}
vis[v]=;
for(j=;j<n;j++)
if(!vis[j] && d[j]>map[v][j])
d[j]=map[v][j];
}
for(i=;i<n;i++) d[]+=d[i];
return d[];
}
heap优化
http://www.nocow.cn/index.php/Prim%E7%AE%97%E6%B3%95
/*
二叉堆优化Prim算法
Author:YangZX
Date:9.11 2011
*/
#include <iostream>
using namespace std;
const int MAXV = , MAXE = , INF = (~0u)>>;
struct edge{
int t, w, next;
}es[MAXE * ];
int h[MAXV], cnt, n, m, heap[MAXV], size, pos[MAXV], dist[MAXV];
void addedge(int x, int y, int z)
{
es[++cnt].t = y;
es[cnt].next = h[x];
es[cnt].w = z;
h[x] = cnt;
} void heapup(int k)
{
while(k > ){
if(dist[heap[k>>]] > dist[heap[k]]){
swap(pos[heap[k>>]], pos[heap[k]]);
swap(heap[k>>], heap[k]);
k>>=;
}else
break;
}
}
void heapdown(int k)
{
while((k<<) <= size){
int j;
if((k<<) == size || dist[heap[(k<<)]] < dist[heap[(k<<)+]])
j = (k<<);
else
j = (k<<) + ;
if(dist[heap[k]] > dist[heap[j]]){
swap(pos[heap[k]], pos[heap[j]]);
swap(heap[k], heap[j]);
k=j;
}else
break;
}
}
void push(int v, int d)
{
dist[v] = d;
heap[++size] = v;
pos[v] = size;
heapup(size);
}
int pop()
{
int ret = heap[];
swap(pos[heap[size]], pos[heap[]]);
swap(heap[size], heap[]);
size--;
heapdown();
return ret;
} int prim()
{
int mst = , i, p;
push(, );
for(i=; i<=n; i++)
push(i, INF);
for(i=; i<=n; i++){
int t = pop();
mst += dist[t];
pos[t] = -;
for(p = h[t]; p; p = es[p].next){
int dst = es[p].t;
if(pos[dst] != - && dist[dst] > es[p].w){
dist[dst] = es[p].w;
heapup(pos[dst]);
heapdown(pos[dst]);
}
}
}
return mst;
}
int main()
{
cin>>n>>m;
for(int i=; i<=m; i++){
int x, y, z;
cin>>x>>y>>z;
addedge(x, y, z);
addedge(y, x, z);
}
cout<<prim()<<endl;
return ;
}