hdu 1879:继续畅通工程

使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),给出城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态,求全省畅通需要的最低成本。

 

最小生成树,和之前一样,kruskal。


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

typedef struct village {
    int v1 , v2 ;
    int cost ;
    int build ;
} vill ;

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

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

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

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 ++) {
            int a1 , a2 , a3 , a4 ;
            scanf("%d%d%d%d" , &a1 , &a2 , &a3 , &a4) ;
            if (a4) {
                Union(a1 , a2) ;
                t -- ; i -- ;
            }
            else {
                vv[i].v1 = a1 ;
                vv[i].v2 = a2 ;
                vv[i].cost = a3 ;
                vv[i].build = 0 ;
            }
        }
        q_sort(1 , t) ;
        for (int i = 1 ; i <= t ; i ++) {
            if (Union(vv[i].v1 , vv[i].v2)) {
                ans += vv[i].cost ;
            }
        }
        cout << ans << endl ;
    }
    return 0 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值