prim算法:
#include<bits/stdc++.h> using namespace std; //input by bxd #define rep(i,a,b) for(int i=(a);i<=(b);i++) #define RI(n) scanf("%d",&(n)) #define RII(n,m) scanf("%d%d",&n,&m) #define RIII(n,m,k) scanf("%d%d%d",&n,&m,&k) #define RS(s) scanf("%s",s); #define LL long long #define REP(i,N) for(int i=0;i<(N);i++) #define CLR(A,v) memset(A,v,sizeof A) ////////////////////////////////// #define inf 900000r #define N 1000 int n,m; int ans; int mp[N][N]; int vis[N]; struct edge { int to;//to为通向的边 int v;//为权值 friend bool operator<(const edge& a,const edge& b) { return a.v>b.v; } }now; void prim(int s) { vis[s]=1; priority_queue<edge>q; while(!q.empty())q.pop(); rep(i,1,n) { rep(j,1,n) if(!vis[j]) { now.to=j; now.v=mp[s][j]; q.push(now); } while(!q.empty()&&vis[q.top().to]) q.pop(); if(q.empty())break; now=q.top();q.pop(); s=now.to; ans+=now.v; vis[s]=1; } } int main() { CLR(vis,0); RII(n,m); rep(i,1,n) rep(j,1,n) mp[i][j]=inf; while(m--) { int a,b,c; RIII(a,b,c); a++;b++; mp[a][b]=mp[b][a]=c; } prim(1); cout<<ans<<endl; return 0; }
原文:https://www.cnblogs.com/bxd123/p/10560965.html