标签:nbsp bsp algo ssi bre eof include out ==
//最小生成树Prim算法 #include <iostream> #include <cstring> using namespace std; const int INF=0x7fffffff/2; int vst[505]; int d[505]; int g[505][505], n, m, ans=0; void read() { int i, j, x, y, w; cin>>n>>m; for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j]=INF; for(i=1; i<=m; i++) { cin>>x>>y>>w; g[x][y]=g[y][x]=w; } } void prim(int v0) { int i, j, k, minn; memset(vst,0,sizeof(vst)); for(i=1; i<=n; i++) d[i]=INF; d[v0]=0; ans=0; for(i=1; i<=n; i++){ minn=INF; for(j=1; j<=n; j++); if(vst[j]==0&&minn>d[j]) { minn=d[j]; k=j; } vst[k]=1; ans+=d[k]; for(j=1; j<=n; j++) if(vst[j]==0&&d[j]>g[k][j]) d[j]=g[k][i]; } } int main(){ read(); prim(1); cout<<ans<<endl; return 0; }
//kruskal算法 #include <iostream> #include <cstring> #include <algorithm> using namespace std; const int maxn=100005; struct Edge{ int x, y, z; }a[maxn]; int n, m, prt[maxn], ans=0,bj; bool cmp(const Edge&x, const Edge&y) { return x.z<y.z; } int getfather(int x){ if(prt[x]==x) return x; prt[x]=getfather(prt[x]); return prt[x]; } void kruskal(){ int f1, f2, k, i; k==0; for(i=1;i<=n;i++) prt[i]=i; for(i=1;i<=m;i++){ f1=getfather(a[i].x); f2=getfather(a[i].y); if(f1!=f2){ ans=ans+a[i].z; prt[f1]=f2; k++; if(k==n-1) break; } } if(k<n-1){ cout<<"Impossible"<<endl; bj=0; return; } } int main() { cin>>n>>m; ans=0;bj=1; for(int i=1; i<=m; i++) cin>>a[i].x>>a[i].x>>a[i].y>>a[i].z; sort(a+1, a+m+1, cmp); kruskal(); if(bj) cout<<ans<<endl; return 0; }
标签:nbsp bsp algo ssi bre eof include out ==
原文地址:https://www.cnblogs.com/2019computer/p/12250713.html