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