演算法›Ch4 圖論演算法第 78 題/共 111 題
78. Kruskal、MST、Union-Find
#AL-04-078易KruskalMSTUnion-Find
題組題幹(本題:(a),共 4 小題)點擊展開
A university plans to connect all campus buildings by fiber links. Each building is a vertex (ID = 0, 1, …, n-1), and each possible fiber link is an undirected edge (a,b) with installation cost w. Assume the cost w is an integer and satisfies . The following C program is designed to find the minimum cost of installing connections from the given links. When two edges have the same cost, the program orders them by (a,b) in increasing order (smaller a first; if a is the same, smaller b first). You must answer Questions 5-8 based on the C program below.
typedef struct { int a, b, w; } E;
static int *P, *S;
static void f0(int n){
P = (int*)malloc(n * sizeof(int));
S = (int*)malloc(n * sizeof(int));
for(int i=0;i<n;i++){ P[i]=i; S[i]=1; }
}
static int f1(int x){
while(P[x]!=x){ P[x]=P[P[x]]; x=P[x]; }
return x;
}
static int f2(int x, int y){
x=f1(x); y=f1(y);
if(x==y) return 0;
if(S[x]<S[y]){ int t=x; x=y; y=t; }
P[y]=x; S[x]+=S[y];
return 1;
}
static int c0(const void *px, const void *py){
const E *x=(const E*)px, *y=(const E*)py;
if(x->w != y->w) return x->w - y->w;
if(x->a != y->a) return x->a - y->a;
return x->b - y->b;
}
int main(void){
int n, m;
if(scanf("%d %d", &n, &m)!=2) return 0;
E *e = (E*)malloc(m * sizeof(E));
for(int i=0;i<m;i++){
scanf("%d %d %d", &e[i].a, &e[i].b, &e[i].w);
if(e[i].a > e[i].b){
int t=e[i].a; e[i].a=e[i].b; e[i].b=t;
}
}
qsort(e, m, sizeof(E), c0);
f0(n);
int *U = (int*)malloc((n-1) * sizeof(int));
int *V = (int*)malloc((n-1) * sizeof(int));
int k=0;
long long total=0;
for(int i=0;i<m && k<n-1;i++){
if(f2(e[i].a, e[i].b)){
U[k]=e[i].a;
V[k]=e[i].b;
total += e[i].w;
k++;
}
}
printf("%lld %d\n", total, k);
free(e); free(U); free(V); free(P); free(S);
return 0;
}
[3%] Which description best matches what the program does to build the backbone?
📄 成大115
▤完整推導請見《WH 資工筆記 · 演算法》Ch4 圖論演算法