POJ 3625题
//朴素的最小生成树:prim算法实现
#include <stdio.h>
#include <string.h>
#include <math.h>
#define arraysize 1001
typedef struct node
{
int x;
int y;
}node;
node nodes[arraysize];
double dis[arraysize][arraysize];
bool final[arraysize];
double d[arraysize];
int n,m;
double sum;
double distance(int x1,int y1,int x2,int y2)
{
return sqrt(double((double)(x1-x2)*(x1-x2)+(double)(y1-y2)*(y1-y2))); //注此处(x1-x2)*(x1-x2)可能超出范围,所以前面加double强制转换(由于这个原因,wa了n此)
}
void Prim()
{
int i,j;
double min;
sum = 0;
int v = 1;
memset(final,0,sizeof(final));
for(i=1;i<n+1;++i)
{
d[i] = dis[1][i];
}
final[1] = true;
d[1] = 0;
for(i=1;i<n;++i)
{
min = 0x7fffffffff; //double类型也可采取这种方式赋值为最大值
for(j=1;j<n+1;j++)
{
if(!final[j] && d[j]<min)
{
v = j;
min = d[j];
}
}
final[v] = true;
sum += min;
for(j=1;j<n+1;++j)
{
if(!final[j] && d[j]>dis[v][j])
d[j] = dis[v][j];
}
}
printf("%.2lf\n",sum); //double类型的输出格式
}
int main()
{
//freopen("1.txt","r",stdin);
scanf("%d%d",&n,&m);
int i,j;
for(i=1;i<n+1;++i)
{
scanf("%d%d",&nodes[i].x,&nodes[i].y);
}
for(i=1;i<n+1;++i)
{
for(j=1;j<n+1;++j)
{
dis[i][j] = distance(nodes[i].x,nodes[i].y,nodes[j].x,nodes[j].y);
}
}
for(i=0;i<m;++i)
{
int start;
int end;
scanf("%d%d",&start,&end);
dis[start][end] = 0; //注此处是双向的
dis[end][start] = 0;
}
Prim();
return 0;
}