hdu 1233:还是畅通工程

给出任意两村庄间的距离,使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小,计算最小的公路总长度。

 

最小生成树,下列代码不知道能不能算kruskal算法。


#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std ;

typedef struct village{
    int v1 , v2 ;
    int dis ;
}vill;

const int MAXN = 105 ;
int fa[MAXN] = {0} ;
vill vv[5000] ;
int n , ans = 0 ;

void init() {
    memset(vv , 0 , sizeof(vv)) ;
    ans = 0 ;
    for (int i = 0 ; i <= n ; i ++) {
        fa[i] = i ;
    }
}

void q_sort(int x , int y) {
    vill key ;
    int i = x , j = y ;
    key = vv[i] ;
    while (i < j) {
        while (i < j && vv[j].dis >= key.dis) j -- ;
        if (i < j) {vv[i] = vv[j] ; i ++ ;}
        while (i < j && vv[i].dis <= key.dis) i ++ ;
        if (i < j) {vv[j] = vv[i] ; j -- ;}
    }
    vv[i] = key ;
    if (x < i - 1) q_sort(x , i - 1) ;
    if (y > j + 1) q_sort(j + 1 , y) ;
}

int find(int x) {
    return (x == fa[x])? x : fa[x] = find(fa[x]) ;
}

bool Union(int x , int y) {
    int fx = find(x) ;
    int fy = find(y) ;
    if (fx == fy) return false ;
    else {
        fa[fy] = fx ;
        return true ;
    }
}

int main() {
    //freopen("in.txt" , "r" , stdin) ;
    while (cin >> n && n) {
        init() ;
        int t = n * (n - 1) / 2 ;
        for (int i = 1 ; i <= t ; i ++) {
            scanf("%d%d%d" , &vv[i].v1 , &vv[i].v2 , &vv[i].dis) ;
        }
        q_sort(1 , t) ;
        for (int i = 1 ; i <= t ; i ++) {
            if (Union(vv[i].v1 , vv[i].v2)) {
                ans += vv[i].dis ;
            }
        }
        cout << ans << endl ;
    }
    return 0 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值