【模板】MST(Prim)
代码如下
#include <bits/stdc++.h>
using namespace std;
const int maxv=2e5+10;
const int maxe=5e5+10;
typedef pair<int,int> P;
inline int read(){
int x=0,f=1;char ch;
do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
return f*x;
}
struct node{
int nxt,to,w;
}e[maxe<<1];
int tot=1,head[maxv];
inline void add_edge(int from,int to,int w){
e[++tot]=node{head[from],to,w},head[from]=tot;
}
int n,m,d[maxv];
bool vis[maxv];
long long ans;
priority_queue<P> q;
void read_and_parse(){
n=read(),m=read();
for(int i=1;i<=m;i++){
int from=read(),to=read(),w=read();
add_edge(from,to,w),add_edge(to,from,w);
}
}
void solve(){
memset(d,0x3f,sizeof(d));
d[1]=0,q.push(make_pair(0,1));
while(q.size()){
int u=q.top().second,cost=q.top().first*-1;q.pop();
if(vis[u])continue;
vis[u]=1,ans+=cost;
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to,w=e[i].w;
if(!vis[v]&&w<d[v]){
d[v]=w;
q.push(make_pair(-d[v],v));
}
}
}
printf("%lld\n",ans);
}
int main(){
read_and_parse();
solve();
return 0;
}