3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5Huge input, scanf is recommended.HintHint
很久以前就写过的题的,当时用的是kruskal写的,觉得麻烦就没用prime写过,前几天长木给讲了一种简单的模板,试了试,挺好理解的。
#include<stdio.h> #include<string.h> #define inf 0x3f3f3f3f int vis[1010]; int dist[1010]; int map[100][100]; int n; int getnext() { int i,pos=-1,dis=inf; for(i=1;i<=n;++i) if(!vis[i]&&dist[i]<dis){ dis=dist[i];pos=i; } return pos; } int prim() { int sum=0,i,u,v; for(i=1;i<=n;++i){ vis[i]=0;dist[i]=inf; } u=1;dist[1]=0; while(u!=-1){ vis[u]=1;sum+=dist[u]; for(i=1;i<=n;++i) if(!vis[i]&&dist[i]>map[u][i]) dist[i]=map[u][i]; u=getnext(); } return sum; } int main () { int m,a,b,c,i; while(scanf("%d",&n),n){ memset(map,0x3f3f3f,sizeof(map)); memset(vis,0,sizeof(vis)); m=n*(n-1)/2; for(i=0;i<m;++i){ scanf("%d%d%d",&a,&b,&c); if(c<map[a][b]) map[a][b]=map[b][a]=c; } printf("%d\n",prim()); } return 0; }
下面是之前用kruskal写的
#include<stdio.h> #include<algorithm> using namespace std; struct app{ int st,ed,w; }; int p[1000]; int find (int x) { return p[x]==x?x:p[x]=find(p[x]); } int mergr(int a,int b) { int x1,x2; x1=find(a); x2=find(b); if(x1!=x2) { p[x1]=x2; return 1; } return 0; } int cmp(app s1,app s2) { return s1.w<s2.w; } int main () { int n,m,sum=0,con,i; app s[10000]; while(scanf("%d",&n),n) { con=0; m=n*(n-1)/2; for(i=1;i<=m;i++) scanf("%d%d%d",&s[i].st,&s[i].ed,&s[i].w); sort(s+1,s+1+m,cmp); for(i=1;i<=n;i++) p[i]=i; for(sum=0,i=1;i<=m;i++) if(mergr(s[i].st,s[i].ed)) { sum=sum+s[i].w; } printf("%d\n",sum); } return 0; }