Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15060 Accepted Submission(s): 6515
3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
3 1 0
#include<stdio.h> #include<algorithm> #define max 50*99+10 using namespace std; int set[110]; struct line { int start; int end; int money; int exist; }num[max]; bool cmp(line a,line b) { return a.money<b.money; } 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,road,need; int i,j,x,y; while(scanf("%d",&city)&&(city!=0)) { for(i=1;i<=city;i++) set[i]=i; road=city*(city-1)/2; for(i=0;i<road;i++) { scanf("%d%d%d%d",&num[i].start,&num[i].end,&num[i].money,&num[i].exist); if(num[i].exist) merge(num[i].start,num[i].end); } sort(num,num+road,cmp); need=0; for(i=0;i<road;i++) { if(find(num[i].start)!=find(num[i].end)) { merge(num[i].start,num[i].end); need+=num[i].money; } } 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,road; int prime() { int i,j,next; int min; int mincost=0; memset(visit,0,sizeof(visit)); for(i=1;i<=city;i++) { lowcost[i]=map[1][i]; } visit[1]=1; for(i=1;i<city;i++) { min=INF; for(j=1;j<=city;j++) { if(!visit[j]&&min>lowcost[j]) { min=lowcost[j]; next=j; } } if(min==INF) break; mincost+=min; visit[next]=1; for(j=1;j<=city;j++) { if(!visit[j]&&lowcost[j]>map[next][j]) { lowcost[j]=map[next][j]; } } } return mincost; } int main() { int i,j,need; int a,b,c,exist; while(scanf("%d",&city)&&(city!=0)) { memset(map,INF,sizeof(map)); road=city*(city-1)/2; for(i=0;i<road;i++) { scanf("%d%d%d%d",&a,&b,&c,&exist); if(exist) map[a][b]=map[b][a]=0; else map[a][b]=map[b][a]=c; } need=prime(); printf("%d\n",need); } return 0; }