Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 6623 | Accepted: 3608 |
Description
Input
Output
Sample Input
1 0 2 3 1 2 37 2 1 17 1 2 68 3 7 1 2 19 2 3 11 3 1 7 1 3 5 2 3 89 3 1 91 1 2 32 5 7 1 2 5 2 3 7 2 4 8 4 5 11 3 5 10 1 5 6 4 2 12 0
Sample Output
0 17 16 26
这算是非常简单的入门题了,有重边,估计大家都能看的出来。
prim代码:#include <stdio.h> #include <string.h> #define MAX 55 #define INF 1000000000 int graph[MAX][MAX] ; bool visited[MAX]; int prim(int n) { int lowCost[MAX] ; for(int i = 1 ; i <= n ; ++i) { lowCost[i] = graph[1][i] ; } memset(visited,false,sizeof(visited)) ; visited[1] = true ; lowCost[0] = INF ; int sum = 0 ; for(int i = 1 ; i < n ; ++i) { int index = 0 ; for(int j = 1 ; j <= n ; ++j) { if(!visited[j] && lowCost[index]>lowCost[j]) { index = j ; } } if(index == 0) 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 n , m ; while(scanf("%d",&n) && n) { scanf("%d",&m); for(int i = 0 ; i < MAX ; ++i) { graph[i][i] = INF ; for(int j = 0 ; j < i ; ++j) { graph[i][j] = graph[j][i] = INF ; } } for(int i = 0 ; i < m ; ++i) { int x, y , len ; scanf("%d%d%d",&x,&y,&len); if(graph[x][y]>len) { graph[x][y] = graph[y][x] = len ; } } int sum = prim(n) ; printf("%d\n",sum) ; } return 0 ; }
kruskal代码:#include <cstdio> #include <algorithm> #define MAX 100000 using namespace std ; struct Edge{ int x , y , w ; }edge[MAX]; int f[MAX] ; void init(int n) { for(int i = 0 ; i <= n ; ++i) { f[i] = i ; } } int find(int x) { int r = x ; while(r != f[r]) { r = f[r] ; } int t ; while(x != r) { t = f[x] ; f[x] = r ; x = t ; } return r ; } bool cmp(const Edge &a , const Edge &b) { return a.w<b.w ; } int kruskal(int n) { sort(edge,edge+n,cmp); int sum = 0 ; for(int i = 0 ; i < n ; ++i) { int fx = find(edge[i].x) , fy = find(edge[i].y) ; if(fx != fy) { sum += edge[i].w ; f[fx] = fy ; } } return sum ; } int main() { int n , m ; while(~scanf("%d",&n) && n) { scanf("%d",&m); init(n) ; for(int i = 0 ; i < m ; ++i) { scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].w) ; } printf("%d\n",kruskal(m)) ; } return 0 ; }
与君共勉