Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 27915 Accepted Submission(s): 12452
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
#include<stdio.h> #include<algorithm> #define max 50*99+10 using namespace std; int set[110]; struct line { int dis; int start; int end; }num[max]; bool cmp(line a,line b) { return a.dis<b.dis; } int find(int p) { int child=p; int t; while(p!=set[p]) p=set[p]; while(child!=p) { t=set[child]; set[child]=p; child=t; } return p; } void merge(int x,int y) { int fx=find(x); int fy=find(y); if(fx!=fy) set[fx]=fy; } int main() { int city,need; int n,i,j; while(scanf("%d",&city)&&(city!=0)) { for(i=1;i<=city;i++) set[i]=i; n=city*(city-1)/2; for(i=0;i<n;i++) { scanf("%d%d%d",&num[i].start,&num[i].end,&num[i].dis); } sort(num,num+n,cmp); need=0; for(i=0;i<n;i++) { if(find(num[i].start)!=find(num[i].end)) { merge(num[i].start,num[i].end); need+=num[i].dis; } } printf("%d\n",need); } return 0; }
#include<stdio.h> #include<string.h> #define INF 0x3f3f3f #define max 100+10 int lowcost[max],map[max][max],visit[max]; int city; int prime() { int i,j; int next;//下一并入点 int min,mincost=0; memset(visit,0,sizeof(visit));//初始化 for(i=1;i<=city;i++) { lowcost[i]=map[1][i]; } visit[1]=1; for(i=2;i<=city;i++) { min=INF; for(j=1;j<=city;j++) { if(!visit[j]&&min>lowcost[j])//找最小权值 { min=lowcost[j]; next=j; } } mincost+=min; visit[next]=1; for(j=1;j<=city;j++) { if(!visit[j]&&lowcost[j]>map[next][j])//更新lowcost数组 { lowcost[j]=map[next][j]; } } } return mincost; } int main() { int road,need; int i,j; int x,y,c; while(scanf("%d",&city)&&(city!=0)) { memset(map,INF,sizeof(map));//初始化 road=city*(city-1)/2; while(road--) { scanf("%d%d%d",&x,&y,&c); map[x][y]=map[y][x]=c; } need=prime(); printf("%d\n",need); } return 0; }