acm.hdu.edu.cn/showproblem.php?pid=1162
最小生成树水题
AC代码:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 110;
int n,m,father[MAX];
struct ink{
double x,y;
}node[MAX];
struct edge{
int from,to;
double cost;
}E[MAX*MAX];
bool cmp(const edge &A, const edge &B){
return A.cost < B.cost;
}
void Init(){
for(int i=0; i<=n; i++)
father[i] = i;
}
int Find(int x){
if(x != father[x])
father[x] = Find(father[x]);
return father[x];
}
int main(){
while(scanf("%d",&n) == 1){
for(int i=0; i<n; i++)
scanf("%lf%lf",&node[i].x,&node[i].y);
int k = 0;
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
E[k].from = i;
E[k].to = j;
E[k++].cost = sqrt(pow(node[i].x - node[j].x, 2) + pow(node[i].y - node[j].y, 2));
}
}
Init();
int cnt = k;
double ans = 0;
sort(E, E+k, cmp);
for(int i=0; i<k && cnt > 1; i++){
int u = E[i].from, v = E[i].to;
int uu = Find(u), vv = Find(v);
if(uu != vv){
father[uu] = vv;
cnt--;
ans += E[i].cost;
}
}
printf("%.2lf\n",ans);
}
return 0;
}