#include<cstdio> #include<queue> #include<cstring> using namespace std; struct my{ int next; int v; int w; }; struct lmjer{ int x,w; bool operator<(const lmjer &rhs)const{ return w>rhs.w; } }; const int nil=0x7f7f7f7f; const int maxn=200000+10; const int maxm=2000000+10; priority_queue<lmjer>Q; int adj[maxn],fa,n,m,dist[maxn]; my bian[maxm]; bool vis[maxn]; void myinsert(int u,int v,int w){ bian[++fa].v=v; bian[fa].next=adj[u]; adj[u]=fa; bian[fa].w=w; } void prim(){ int cost=0; lmjer u; u.x=1; u.w=0; Q.push(u); int tt=0; while(!Q.empty()&&tt<n){ lmjer x=Q.top(); Q.pop(); if(vis[x.x]) continue; vis[x.x]=true; tt++; cost+=x.w; for(int i=adj[x.x];i;i=bian[i].next){ int v=bian[i].v; if(!vis[v]){ lmjer tmp; tmp.x=v; tmp.w=bian[i].w; Q.push(tmp); } } } printf("%d",cost); } int main(){ int u,v,w; scanf("%d%d",&n,&m); for (int i=1;i<=m;i++){ scanf("%d%d%d",&u,&v,&w); myinsert(u,v,w); myinsert(v,u,w); } prim(); return 0; }
原文地址:https://www.cnblogs.com/lmjer/p/9392444.html
时间: 2024-10-24 01:59:33