hdu 1233:还是畅通工程

来源:互联网 发布:jdbc连接两个数据库 编辑:程序博客网 时间:2024/06/01 10:18

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

 

最小生成树,下列代码不知道能不能算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 ;}


0 0