Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18699 Accepted Submission(s): 7923
3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
#include<stdio.h> #include<algorithm> using namespace std; int set[110]; struct line { int start; int end; int money; }num[1010]; 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 road,city,need; int i,j; int exist;//用于判断是否全部连通 while(scanf("%d%d",&road,&city)&&(road!=0)) { for(i=1;i<=city;i++) set[i]=i; for(i=1;i<=road;i++) { scanf("%d%d%d",&num[i].start,&num[i].end,&num[i].money); } sort(num+1,num+road+1,cmp); need=0; for(i=1;i<=road;i++) { if(find(num[i].start)!=find(num[i].end)) { merge(num[i].start,num[i].end); need+=num[i].money; } } exist=0; for(i=1;i<=city;i++) { if(set[i]==i)//只有根节点的父节点才是自己 { exist++; } } if(exist>1)//多了,证明没有全部连通 printf("?\n"); else printf("%d\n",need); } return 0; }
#include<stdio.h> #include<string.h> #define INF 0x3f3f3f int lowcost[110],visit[110],map[110][110]; int city; void prime() { int i,j; int next,min,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)//遍历全部找不到与该点连通的线路 { printf("?\n"); return ;//程序结束 } mincost+=min; visit[next]=1; for(j=1;j<=city;j++) { if(!visit[j]&&lowcost[j]>map[next][j]) { lowcost[j]=map[next][j]; } } } printf("%d\n",mincost); } int main() { int road,need; int i,j,x,y,c; while(scanf("%d%d",&road,&city)&&(road!=0)) { memset(map,INF,sizeof(map)); while(road--) { scanf("%d%d%d",&x,&y,&c); map[x][y]=map[y][x]=c; } prime(); } return 0; }