标签:hdu3371 最小生成树 kruskal prim connect the cities
1 6 4 3 1 4 2 2 6 1 2 3 5 3 4 33 2 1 2 2 1 3 3 4 5 6
1
#include <stdio.h> #include <string.h> #define MAX 550 #define INF 100000000 int graph[MAX][MAX] ; int prim(int n) { int sum = 0 ,lowCost[MAX] ; bool visited[MAX] ; memset(visited,false,sizeof(visited)) ; for(int i = 1 ; i <= n ; ++i) { lowCost[i] = graph[1][i] ; } visited[1] = true ; for(int i = 1 ; i < n ; ++i) { int min = INF , index = -1 ; for(int j = 1 ; j <= n ; ++j) { if(!visited[j] && min>lowCost[j]) { min = lowCost[j] ; index = j ; } } if(index == -1) { if(i < n) { return INF ; } break ; } sum += lowCost[index] ; visited[index] = true ; for(int j = 1 ; j <= n ; ++j) { if(!visited[j] && lowCost[j]>graph[index][j]) { lowCost[j] = graph[index][j] ; } } } return sum ; } int main() { int t ; scanf("%d",&t); while(t--) { int n , m , k; scanf("%d%d%d",&n,&m,&k) ; for(int i = 1 ; i <= n ; ++i) { graph[i][i] = 0 ; for(int j = 1 ; j < i ; ++j) { graph[i][j] = graph[j][i] = INF ; } } for(int i = 0 ; i < m ; ++i) { int x, y ,w ; scanf("%d%d%d",&x,&y,&w) ; if(w<graph[x][y]) { graph[x][y] = graph[y][x] = w; } } int p[MAX] ; for(int i = 0 ; i < k ; ++i) { int t ; scanf("%d",&t); for(int j = 0 ; j < t ; ++j) { scanf("%d",&p[j]); } for(int j = 0 ; j < t ; ++j) { for(int r = 0 ; r < j ; ++r) { graph[p[j]][p[r]] = graph[p[r]][p[j]] = 0 ; } } } int sum = prim(n) ; if(sum >= INF) { puts("-1") ; } else { printf("%d\n",sum) ; } } return 0 ; }
#include <cstdio> #include <algorithm> #include <cstring> #define MAX 550 #define INF 1000000000 using namespace std ; struct Edge{ int x , y , w ; }edge[MAX*MAX]; bool cmp(const Edge &e1 , const Edge &e2) { return e1.w<e2.w ; } int f[MAX] ; int find(int x) { int r = x ; while(r != f[r]) { r = f[r] ; } int temp ; while(x != f[x] ) { temp = f[x] ; f[x] = r ; x = temp ; } return r ; } void init() { for(int i = 0 ; i < MAX ; ++i) { f[i] = i ; } } int kruskal(int n , int m) { sort(edge,edge+n,cmp) ; init(); int sum = 0 ,count = 0; for(int i = 0 ; i < n ; ++i) { int x = find(edge[i].x) , y = find(edge[i].y) ; if(x != y) { count++ ; sum += edge[i].w; f[x] = f[y] ; } } if(count<m-1) { return INF ; } return sum ; } int main() { int t ; scanf("%d",&t); while(t--) { int n , m , k; scanf("%d%d%d",&n,&m,&k) ; int index = 0 ; for(int i = 0 ; i < m ; ++i) { int x, y ,w ; scanf("%d%d%d",&x,&y,&w) ; edge[index].x = x , edge[index].y = y , edge[index++].w = w ; } int p[MAX] ; for(int i = 0 ; i < k ; ++i) { int t ; scanf("%d",&t); for(int j = 0 ; j < t ; ++j) { scanf("%d",&p[j]); } for(int j = 0 ; j < t ; ++j) { for(int r = 0 ; r < j ; ++r) { edge[index].x = p[j] , edge[index].y = p[r] , edge[index++].w = 0 ; } } } int sum = kruskal(index,n) ; if(sum >= INF) { puts("-1") ; } else { printf("%d\n",sum) ; } } return 0 ; }
hdu 3371 Connect the Cities Prim + Kruskal两种算法分别AC 水过~~~~
标签:hdu3371 最小生成树 kruskal prim connect the cities
原文地址:http://blog.csdn.net/lionel_d/article/details/43916653