最小生成树示例程序_Prim算法

May 3, 2013
Graph

输入:顶点个数n和边数m,然后是m条边的数据。u v w 分别代表两个顶点和权值。顶点从1开始记起。 输出:一次选择的各条边和最小生成树的权。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long int LL;
const int MAXN =  0x3f3f3f3f;
const int  MIN =  -0x3f3f3f3f;
const double eps = 1e-9;
const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
  {1,1},{1,-1},{-1,-1}};
const int MAX = 100;
int n, m, lowcost[MAX], nearvex[MAX], edge[MAX][MAX];
void prim(int u0)
{
  int i, j, sum = 0;
  for (i = 1; i <= n; ++i) {
    lowcost[i] = edge[u0][i]; nearvex[i] = u0;
  }
  nearvex[u0] = -1;
  for (i = 1; i < n; ++i) {
    int min = MAXN, v = -1;
    for (j = 1; j <= n; ++j) {
      if (nearvex[j] != -1 && lowcost[j] < min) {
        min = lowcost[j]; v = j;
      }
    }
    if (v != -1) {
      printf("%d %d %d\n", nearvex[v], v, lowcost[v]);
      sum += lowcost[v];
      nearvex[v] = -1;
      for (j = 1; j <= n; ++j) {
        if (nearvex[j] != -1 && lowcost[j] > edge[v][j]) {
          lowcost[j] = edge[v][j]; nearvex[j] = v;
        }
      }
    }
  }
  printf("MST sum is : %d\n", sum);
}

int main(void){
#ifndef ONLINE_JUDGE
  freopen("prim.in", "r", stdin);
#endif
  while (~scanf("%d%d", &n, &m)) {
    int i, j, u, v, w;
    memset(edge, 0, sizeof(edge));
    for (i = 1; i <= m; ++i) {
        scanf("%d%d%d", &u, &v, &w);
        edge[u][v] = edge[v][u] = w;
    }
    for (i = 1; i <= n; ++i) {
      for (j = 1; j <= n; ++j) {
        if (i == j) edge[i][j] = 0;
        else if (edge[i][j] == 0) edge[i][j] = MAXN;
      }
    }
    prim(1);
  }

  return 0;
}

写代码的时候,还是会出现各种错误,比如for循环里面到底是不是要取到等号,一定要想清楚,还有就是细节,输入的m和n不要搞错了。

comments powered by Disqus