代码实现
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 5000;
struct edge{
int u;
int v;
int c;
};
edge edges[maxn];
int father[maxn];
int n;
int m;
bool cmp(edge a,edge b){
return a.c < b.c;
}
int find(int x){
if(father[x]==x){
return x;
}else{
int root = find(father[x]);
father[x] =root;
return root;
}
}
int main(){
while(scanf("%d",&n)!=EOF&&n!=0){
m = (n*(n-1))/2;
int cost=0;
int cnt=0;
int u,v,c,status;
for(int i=0;i<m;i++){
scanf("%d %d %d %d",&u,&v,&c,&status);
if(status==1){
c = 0;
}
edges[i].u = u;
edges[i].v = v;
edges[i].c = c;
}
for(int i=0;i<=n;i++){
father[i] = i;
}
sort(edges,edges+m,cmp);
for(int i=0;i<m;i++){
int u = edges[i].u;
int v = edges[i].v;
int c = edges[i].c;
int fatherU = find(u);
int fatherV = find(v);
if(fatherU == fatherV){
continue;
}else{
father[fatherU] = fatherV;
cost += c;
cnt++;
if(cnt==n-1){
printf("%d\n",cost);
break;
}
}
}
}
return 0;
}
码后反思
- 模板题。。。