堆优化的prim算法
#include<queue>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
const int INF=0x3f3f3f3f; //定义无穷大
struct{
int to;
int next;
int value;//前向星存图
}c[400000];
int n,m;
int len=0;
int head[10000];
int via[10000]={0};
int d[10000];//当前点到已经选取为最小生成树的集合的最短距离
priority_queue < pair<int ,int>, vector<pair<int ,int> > ,greater<pair<int ,int> > > q;
int ans=0;
void prime(int s)
{
fill(d,d+10000,INF);
d[s]=0;
q.push(make_pair(d[s],s));
while(!q.empty())
{
int u=q.top().second;
int di=q.top().first;
q.pop();
if(di!=d[u]) continue;
if(via[u]==0) //每次选取离集合最近的一个未被访问的点
{
ans+=di;
via[u]=1;
for(int i=head[u];i!=-1;i=c[i].next)
{
int v=c[i].to;
if(d[v]>c[i].value)
{
d[v]=c[i].value;
q.push(make_pair(d[v],v));
}
}
}
}
}
int main()
{
fill(head,head+10000,-1);
cin>>n>>m;
int x,y,e;
for(int i=0;i<m;i++)
{
cin>>x>>y>>e;
c[len].next=head[x];
c[len].to=y;
c[len].value=e;
head[x]=len++;
c[len].next=head[y];
c[len].to=x;
c[len].value=e;
head[y]=len++;
}
prime(1);
int flag=1;
for(int i=1;i<=n;i++)//判断是否联通
{
if(via[i]==0)
{
flag=0;
break;
}
}
if(flag==1)
{
cout<<ans;
}
else cout<<"orz";
return 0;
}