kruskal
#include <bits/stdc++.h> using namespace std; const int maxx=0x3f3f3f3f; const int maxn=10000; struct node { int u,v,l; bool operator <(const node &a)const { return l<a.l; } }edge[maxn]; int father[maxn]; int nodenum,edgenum; void init() { for(int i=0;i<nodenum;i++) { father[i]=i; } } int Find(int x) { if(x==father[x])return x; return father[x]=Find(father[x]); } void Union(int x,int y) { int temp_x=Find(x); int temp_y=Find(y); if(temp_x!=temp_y) { father[temp_x]=temp_y; } } int kruskal() { sort(edge,edge+edgenum); init(); node now; int ans=0; for(int i=0;i<edgenum;i++) { now=edge[i]; if(Find(now.u)!=Find(now.v)) { Union(now.u,now.v); ans+=now.l; } } return ans; } int main() { while(scanf("%d %d",&edgenum,&nodenum)&&edgenum) { for(int i=0;i<edgenum;++i) { scanf("%d %d %d",&edge[i].u,&edge[i].v,&edge[i].l); } int ans=kruskal(); bool flag=0; for(int i=2;i<=nodenum;i++) { if(Find(1)!=Find(i)) { flag=1; break; } } if(flag) { cout<<"?"<<'\n'; } else { cout<<ans<<'\n'; } } return 0; }
prim
#include <bits/stdc++.h> #define INF 0x7f7f7f7f using namespace std; int mp[150][150]; int dis[150]; int vis[150]; int nodenum,edgenum; int prim(int src) { for(int i=1; i<=nodenum; i++) { dis[i]=mp[src][i]; } int sum=0; vis[src]=1; dis[src]=0; for(int i=2; i<=nodenum; i++) { int pos=-1; int MIN=INF; for(int j=1; j<=nodenum; j++) { if(dis[j]<MIN&&!vis[j]) { pos=j; MIN=dis[j]; } } if(pos==-1) { return -1; } sum+=MIN; vis[pos]=1; for(int j=1; j<=nodenum; j++) { if(!vis[j]&&dis[j]>mp[pos][j]) { dis[j]=mp[pos][j]; } } } return sum; } int main() { int a,b,c; while(scanf("%d %d",&edgenum,&nodenum)&&edgenum) { memset(mp,INF,sizeof(mp)); memset(dis,INF,sizeof(dis)); memset(vis,0,sizeof(vis)); for(int i=0; i<edgenum; i++) { scanf("%d %d %d",&a,&b,&c); mp[a][b]=min(mp[a][b],c); mp[b][a]=min(mp[a][b],c); } int ans=prim(1); if(ans==-1) { cout<<"?"<<'\n'; } else { cout<<ans<<'\n'; } } }
来源:https://www.cnblogs.com/guanwen769aaaa/p/11246979.html