HDU 1863 畅通工程

http://acm.hdu.edu.cn/showproblem.php?pid=1863

 

解题思路:prim算法,统计所有的点有没有都加入到最小生成树中,有就输出sum值,没有就?

 

 

#include <stdio.h> #include <string.h> #define size 105 #define INIT 999999 int count; int Graph[size][size]; long sum; void Prim(int villige) { int i,j; int min,locate; int dist[size]; sum=0; bool visited[size]; memset(visited,0,sizeof(visited)); memset(dist,INIT,sizeof(dist)); for(i=1;i<=villige;i++) dist[i] = Graph[1][i]; visited[i] = true; count = 1; for (j=2;j<=villige;j++) { min = INIT; for(i=2;i<=villige;i++) { if (!visited[i]&&dist[i]<min) { min = dist[i]; locate = i; } } if(min!=INIT) { visited[locate] = true; sum+=min; count++; for (i=1;i<=villige;i++) { if(!visited[i]&&Graph[locate][i]!=0&&dist[i]>Graph[locate][i]) dist[i] = Graph[locate][i]; } } else return ; } } int main() { int road,villige; int i,j,weight; while (scanf("%d%d",&road,&villige)!=EOF&&road) { count = 0; for(i=0;i<=villige;i++) { for(j=0;j<=villige;j++) if(i==j) Graph[i][j] = 0; else Graph[i][j] = INIT; } while (road--) { scanf("%d%d%d",&i,&j,&weight); Graph[i][j] = weight; Graph[j][i] = weight; } Prim(villige); if(count==villige) printf("%ld/n",sum); else printf("?/n"); } return 0; }

 

 

 

你可能感兴趣的:(HDU 1863 畅通工程)