Chinaunix首页 | 论坛 | 博客
  • 博客访问: 436552
  • 博文数量: 103
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 971
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-11 17:22
文章分类
文章存档

2008年(77)

2007年(26)

我的朋友

分类: C/C++

2008-04-07 14:51:52

#include <stdio.h>
#include <string.h>
int edge[51][51], point[51], key[51], p, r, sum;
static int init(void);
static int prim(void);
int main(int argc, char **argv)
{
        while(scanf("%d", &p), p != 0){
                scanf("%d", &r);
                getchar();
                init();
                printf("%d\n", prim());
        }
        return 0;
}

static int prim(void)
{
        int i, j, k, min, node, tempmin;

        point[1] = j = node = 1;
        for(i = 1; i <= p; i++){
                min = 100;
                tempmin = 0;
                for(k = 1; k <= p; k++){
                        if(point[k]){
                                continue;
                        }
                        if(edge[k][j] && key[k] > edge[k][j]){
                                key[k] = edge[k][j];
                        }
                        if(key[k] < min){
                                tempmin = min = key[k];
                                node = k;
                        }
                }
                sum += tempmin;
                point[node] = 1;
                j = node;
        }
        return sum;
}

static int init(void)
{
        int i, row, col, weight;

        memset(edge, 0, sizeof(edge));
        memset(point, 0, sizeof(point));
        memset(key, 100, sizeof(key));
        sum = 0;
        for(i = 1; i <= r; i++){
              scanf("%d %d %d", &row, &col, &weight);
              getchar();
              if(edge[row][col] == 0 || edge[row][col] > weight){
                    edge[row][col] = edge[col][row] = weight;
              }
         }
        return 0;
}

阅读(703) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~