Build The Electric System
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2966
prim:
View Code
1 #include<stdio.h> 2 #include<string.h> 3 const int INF = 1<<28 ; 4 #define maxn 510 5 int map[maxn][maxn], dis[maxn], visited[maxn] ; 6 int main() 7 { 8 int t, a, b, k, n, e, minco, min ; 9 int i, j ; 10 int tt ; 11 scanf("%d", &t) ; 12 while(t--) 13 { 14 memset(visited, 0, sizeof(visited)) ; 15 minco = 0 ; 16 scanf("%d%d", &n, &e) ; 17 for(i=0; i<n; i++) 18 { 19 for(j=0; j<n; j++) 20 { 21 map[i][j] = INF ; 22 } 23 } 24 for(i=0; i<e; i++) 25 { 26 scanf("%d%d%d",&a, &b, &k) ; 27 map[a][b] = map[b][a] = k ; 28 } 29 for(j=0; j<n; j++) 30 dis[j] = map[0][j] ; 31 visited[0] = 1 ; 32 for(i=0; i<n; i++) 33 { 34 min = INF ; 35 for(j=0; j<n; j++) 36 { 37 if(!visited[j]&&min>dis[j]) 38 { 39 min = dis[j] ; 40 tt = j ; 41 } 42 } 43 if(min!=INF) 44 minco += min ; 45 visited[tt] = 1 ; 46 for(j=0; j<n; j++) 47 { 48 if(!visited[j]&&dis[j]>map[tt][j]) 49 { 50 dis[j] = map[tt][j] ; 51 } 52 } 53 } 54 printf("%d\n", minco) ; 55 } 56 return 0 ; 57 }