标签:
题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1233
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 40310 Accepted Submission(s):
18325
1 #include<cstdio> 2 #include<string.h> 3 #include<algorithm> 4 using namespace std; 5 #define inf 0x3f3f3f3f 6 int map[105][105]; 7 int prim(int n) 8 { 9 int vis[105], dis[105]; 10 int ans = 0; 11 memset(vis, 0, sizeof(vis));//记录该点是否被访问过 12 memset(dis, inf, sizeof(dis)); 13 dis[1] = 0;//从第一个点开始至第n个点 14 for(int i = 1; i <= n; i++) 15 { 16 int k = -1, tp = inf; 17 for(int j = 1; j <= n; j++) 18 //寻找权最小的路 19 if(!vis[j] && dis[j] < tp) 20 { 21 k = j;//最小权连通的点(还未标记的) 22 tp = dis[j];//最小的权的大小(记为x) 23 } 24 vis[k] = 1;//标记新的点 25 ans += tp;//加入新的权值 26 for(int j = 1; j <= n; j++) 27 { //寻找新的最小权值 (仅次于x小的权值) 28 if(!vis[j] && map[k][j] < dis[j]) 29 dis[j] = map[k][j]; 30 } 31 } 32 return ans; 33 } 34 int main() 35 { 36 int n, m, a, b, c; 37 while( scanf("%d", &n), n) 38 { //初始化地图上的权,设为最大值 39 memset(map, inf, sizeof(map)); 40 m = n * (n - 1) / 2; 41 for(int i = 0; i < m; i++){ 42 scanf("%d %d %d", &a, &b, &c); 43 map[a][b] = map[b][a] = c;//无向图 44 } 45 printf("%d\n", prim(n)); 46 } 47 return 0; 48 }
标签:
原文地址:http://www.cnblogs.com/123tang/p/5746521.html