码迷,mamicode.com
首页 > 其他好文 > 详细

公路村村通(30)

时间:2015-06-12 19:15:09      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

用了Kruskal算法来生成最小生成树

当然也可以用Prim算法来做

#include <iostream>
using namespace std;
typedef struct{
    int start;
    int end;
    int length;
}road;

int* father;
road* map;
int n, m;
int countRoad = 0, sum = 0;

int roadCompare(const void* a, const void* b);
int findFather(int i);
int main()
{
    cin >> n >> m;
    map = (road *)malloc((m + 1)*sizeof(road));
    father = (int*)malloc((n + 1)*sizeof(int));

    for (int i = 1; i <= m; i++){
        cin >> map[i].start >> map[i].end >> map[i].length;
    }
    for (int i = 1; i <= n; i++){
        father[i] = i;
    }
    qsort(map + 1, m, sizeof(road), roadCompare);

    //Kruskal核心算法
    for (int i = 1; i <= m; i++){
        if (findFather(map[i].start) != findFather(map[i].end)){
            countRoad++;
            sum += map[i].length;
            father[findFather(map[i].start)] = findFather(map[i].end);
        }
        if (countRoad == n - 1){
            break;
        }
    }

    if (countRoad != n - 1){
        cout << -1 << endl;
    }
    else{
        cout << sum << endl;
    }

    return 0;
}
int roadCompare(const void* a, const void* b)
{
    int c = (*(road*)a).length - (*(road*)b).length;
    if (c > 0){
        return 1;
    }
    else if (c == 0){
        return 0;
    }
    else return -1;
}
int findFather(int i)
{
    if (father[i] == i){
        return i;
    }
    else{
        return father[i] = findFather(father[i]);
    }
}

 

公路村村通(30)

标签:

原文地址:http://www.cnblogs.com/zhouyiji/p/4572283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!