这题好像更新了呀,不压缩路径的话,find函数用递归的话会栈溢出。
#include <stdio.h>
#include<stdbool.h>
#include<stdlib.h>
int set[101];
typedef struct node{
int length;
int e1;
int e2;
}edge;
void init_set(int* set){
for(int i=0;i<101;i++){
set[i]=i;
}
}
int get_father(int set[], int i){
if(set[i] != i)
set[i] = get_father(set, set[i]);
return set[i];
}
bool judge_same(int set[],edge i){
int x=get_father(set, i.e1);
int y=get_father(set,i.e2);
if(x==y) return true;
return false;
}
void merge_set(int set[],edge i){
int x=get_father(set, i.e1);
int y=get_father(set,i.e2);
if(x>y){
set[x]=y;
}else{
set[y]=x;
}
}
int cmp(const void* a,const void* b){
edge* e1=(edge*)a;
edge* e2=(edge*)b;
return e1->length -e2->length;
}
int main() {
int n;
while(scanf("%d",&n)!=EOF){
if(n==0) break;
init_set(set);
edge* e=(edge*)malloc(sizeof(edge)*(n*(n-1))/2);
for(int i=0;i<(n*(n-1))/2;i++){
scanf("%d %d %d\n",&e[i].e1,&e[i].e2,&e[i].length);
}
qsort(e,(n*(n-1))/2,sizeof(e[0]),cmp);
int sum=0;
for(int i=0;i<(n*(n-1))/2;i++){
if(!judge_same(set, e[i])){
sum+=e[i].length;
merge_set(set, e[i]);
}
}
printf("%d\n",sum);
}
return 0;
}
结果:
标签:KY148,set,工程,int,void,edge,畅通,include,e1 From: https://www.cnblogs.com/llllmz/p/18050325