HDU 1162 Eddy's picture
最小生成树..
#include <iostream>
#include <string.h>
#include <math.h>
#include <iomanip>
using namespace std;
const int MAXN = 101;
struct point {
double x,y;
};
point p[MAXN];
double G[MAXN][MAXN];
double lowcost[MAXN];
int closest[MAXN];
bool used[MAXN];
double cost;
void PRIM(int n){
cost = 0;
used[1] = true;
for(int i = 2; i <= n; i++){
lowcost[i] = G[1][i];
closest[i] = 1;
used[i] = false;
}
double min;
int minIndex;
for(int i = 1; i < n; i++){
min = 32767.0;
for(int j = 1; j <= n; j++){
if( !used[j] && min > lowcost[j] ){
min = lowcost[j];
minIndex = j;
}
}
used[minIndex] = true;
cost += min;
for(int j = 1; j <= n;j++){
if( !used[j] && G[minIndex][j] < lowcost[j])
lowcost[j] = G[minIndex][j];
}
}
}
int main(){
int N;
double x,y,dis;
while(scanf("%d",&N) == 1){
for(int i = 1; i <= N; i++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
memset(G,0,sizeof(G));
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
G[i][j] = sqrt((p[i].x-p[j].x)*(p[i].x-p[j].x)+(p[i].y-p[j].y)*(p[i].y-p[j].y));
PRIM(N);
printf("%.2f\n",cost);
}
return 0;
}