#include <bits/stdc++.h> using namespace std; const int maxn=100000+15; const int maxm=100000+15; struct Edge { int x,y,z,next; Edge(int x=0,int y=0,int z=0,int next=0):x(x),y(y),z(z),next(next) {} }edge[maxm*2]; const bool operator < (const Edge &a,const Edge &b) { return a.z>b.z; } int n,m; int sumedge,head[maxn]; int ins(int x,int y,int z) { edge[++sumedge]=Edge(x,y,z,head[x]); return head[x]=sumedge; } priority_queue <Edge> que; int ans; bool boo[maxn]; int main() { scanf("%d%d",&n,&m); for (int i=1;i<=m;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); ins(x,y,z); ins(y,x,z); } memset(boo,false,sizeof(boo)); boo[1]=true; for (int u=head[1];u;u=edge[u].next) que.push(edge[u]); for (int i=1;i<n;i++) //总共有n-1条边 { Edge temp; temp=que.top(); for (;boo[temp.y];que.pop(),temp=que.top()); que.pop(); ans+=temp.z; boo[temp.y]=true; for (int u=head[temp.y];u;u=edge[u].next) if (!boo[edge[u].y]) que.push(edge[u]); } printf("%d\n",ans); return 0; }
原文:http://www.cnblogs.com/9pounds15pence/p/6349672.html