Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32489 Accepted Submission(s): 14618
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
<span style="font-size:12px;">#include<cstdio> #include<algorithm> using namespace std; int set[5000],n,m; struct node { int x,y,w; }row[5000]; int cmp(node a,node b) { return a.w<b.w; } int find(int x) { int r=x,t; while(r!=set[r]) r=set[r]; while(r!=x) { t=set[x]; set[x]=r; x=t; } return r; } int merge(int a,int b) { int fa,fb; fa=find(a); fb=find(b); if(fa!=fb) { set[fa]=fb; return 1; } return 0; } int main() { int i,sum; while(scanf("%d",&n)&&n) { m=n*(n-1)/2; for(i=1;i<=n;i++) set[i]=i; for(i=0;i<m;i++) scanf("%d%d%d",&row[i].x,&row[i].y,&row[i].w); sort(row,row+m,cmp); sum=0; for(i=0;i<m;i++) { if(merge(row[i].x,row[i].y)) sum+=row[i].w; } printf("%d\n",sum); } return 0; }</span>
prim算法,代码如下:
<span style="font-size:12px;">#include<cstdio> #include<cstring> #define INF 0x3f3f3f #define max 110 int map[max][max],n,sum; void prim() { int next,i,j,min; sum=0; int lowcost[max],visit[max]; memset(visit,0,sizeof(visit)); for(i=1;i<=n;++i) lowcost[i]=map[1][i]; visit[1]=1; for(i=2;i<=n;++i) { min=INF; for(j=1;j<=n;++j) { if(!visit[j]&&min>lowcost[j]) { min=lowcost[j]; next=j; } } sum+=lowcost[next]; visit[next]=1; for(j=1;j<=n;++j) { if(!visit[j]&&lowcost[j]>map[next][j]) lowcost[j]=map[next][j]; } } } int main() { int m,i,x,y,c; while(scanf("%d",&n)&&n) { m=n*(n-1)/2; while(m--) { scanf("%d%d%d",&x,&y,&c); map[x][y]=map[y][x]=c; } prim(); printf("%d\n",sum); } return 0; } </span>