模板题啦。
虽然Prim在解决某些特殊情形时有用,但一般Kruskal就够了。
#include<bits/stdc++.h> using namespace std; #define ll long long /* Kruskal begin */ const int MAXN=5005; const int MAXM=200005; int F[MAXN]; struct Edge{ int u,v,w; }edge[MAXM]; int tol; void add_edge(int u,int v,int w){ edge[tol].u=u; edge[tol].v=v; edge[tol++].w=w; } bool cmp(Edge a,Edge b){ return a.w<b.w; } int find(int x){ if(F[x]==-1) return x; else return F[x]=find(F[x]); } ll Kruskal(int n){ memset(F,-1,sizeof(F)); sort(edge,edge+tol,cmp); int cnt=0; int ans=0; for(int i=0;i<tol;i++){ int u=edge[i].u; int v=edge[i].v; int w=edge[i].w; int t1=find(u); int t2=find(v); if(t1!=t2){ ans+=w; F[t1]=t2; cnt++; } if(cnt==n-1) break; } if(cnt<n-1) return -1e18; return ans; } /* Kruskal end */ int main(){ int n,m; while(~scanf("%d%d",&n,&m)){ for(int i=0;i<m;i++){ int u,v,w; scanf("%d%d%d",&u,&v,&w); add_edge(u,v,w); } ll ans=Kruskal(n); if(ans<=-1e18){ printf("orz "); } else{ printf("%lld ",ans); } } }