#include <iostream>
#include <algorithm>
#include <string.h>
#include <queue>
using namespace std;
const int inf=0x3f3f3f3f;;
const int maxx=1e3+100;;
const int maxn=2e6+10;
typedef long long ll;
int m,n,q,ans,sum;
int dis[maxx];
int sto[maxx];
int head[2*maxn];
bool vis[maxx];
int a[maxx][maxx];
struct point{
int to;
int next;
int val;
bool operator < (const point &a) const
{
return val>a.val;
}
};
point pt[2*maxn];
void add(int u,int v,int val)
{
pt[q].next=head[u];
pt[q].to=v;
pt[q].val=val;
head[u]=q++;
}
void prim(int st)
{
priority_queue<point>q;
point t1,t2;
int w,v;
memset(dis,inf,sizeof(dis));
memset(vis,false,sizeof(vis));
for (int i=head[st];i!=-1;i=pt[i].next)
{
int v=pt[i].val;
if (dis[pt[i].to]>v)
{
dis[pt[i].to]=v;
t1.to=pt[i].to;
t1.val=v;
q.push(t1);
}
}
vis[st]=true;
ans=1;sum=0;
while (!q.empty())
{
point t=q.top();
q.pop();
int v=t.to;
if (vis[v])continue;
vis[v]=true;
sum+=dis[v];
ans++;
for (int i=head[v];i!=-1;i=pt[i].next)
{
int u=pt[i].to;
if (!vis[u]&&pt[i].val<dis[u])
{
dis[u]=pt[i].val;
t2.to=u;
t2.val=pt[i].val;
q.push(t2);
}
}
}
}
int main()
{
int k,u,v,val,st;
cin>>m>>n>>k;
memset(head,-1,sizeof(head));
q=1;
for (int i=0;i<m;i++)
{
cin>>u>>v>>val;
add(u,v,val);
add(v,u,val);
st=u;
}
prim(st);
if (ans==n)
cout<<sum<<endl;
else
cout<<"don't exit "<<endl; //没有
return 0;
}
最小生成树prim+邻接表优化
最新推荐文章于 2023-07-09 10:13:46 发布