标签:hdu1879 继续畅通工程 acm 最小生成树 prim
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 <string.h> #define MAX 110 #define INF 100000000 int graph[MAX][MAX] ; bool visited[MAX] ; int prim(int n) { int closest[MAX] ; int lowcost[MAX] ; memset(visited,false,sizeof(visited)) ; for(int i = 1 ; i <= n ; ++i) { closest[i] = 1; lowcost[i] = graph[1][i] ; } visited[1] = true ; for(int i = 1 ; i <= n ; ++i) { int temp = INF ; int t = 1 ; for(int j = 1 ; j <= n ; ++j) { if(!visited[j] && temp>lowcost[j]) { temp = lowcost[j] ; t = j ; } } if(temp == INF) { break ; } visited[t] = true ; for(int j = 1 ; j <= n ; ++j) { if(!visited[j] && lowcost[j]>graph[t][j]) { lowcost[j] = graph[t][j] ; closest[j] = t ; } } } int sum = 0 ; for(int i = 2 ; i <= n ; ++i) { sum += lowcost[i] ; } return sum ; } int main() { int n = 0 ; while(scanf("%d",&n) && n) { int m = (n*(n-1))/2 ; for(int i = 0 ; i <= n ; ++i) { for(int j = 0 ; j <= i ; ++j) { graph[i][j] = graph[j][i] = INF ; } } for(int i = 1 ; i <= m ; ++i) { int x,y,w,flag; scanf("%d%d%d%d",&x,&y,&w,&flag); if(flag) { graph[x][y] = graph[y][x] = 0; } else { graph[x][y] = graph[y][x] = w ; } } int ans = prim(n); printf("%d\n",ans) ; } return 0 ; }
标签:hdu1879 继续畅通工程 acm 最小生成树 prim
原文地址:http://blog.csdn.net/lionel_d/article/details/43899505