prim算法最小生成树,一开始把所有点之间的距离算出来保存到邻接矩阵中,然后使用prim计算最小生成树。prim点集,kruskal边集。
#include<iostream>
#include<math.h>
using namespace std;
#define MAXNUM 101
#define INF 999999
struct point{
double x;
double y;
}p[MAXNUM];
int n;
bool visit[MAXNUM];
double dis[MAXNUM][MAXNUM];
double edge[MAXNUM];
double distance(int i,int j){
return 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));
}
void input(){
int i;
cin >> n;
for(i=1;i<=n;i++){
cin >> p[i].x >> p[i].y;
}
}
void init(){
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++){
dis[i][j] = distance(i,j);
}
memset(visit,false,MAXNUM);
}
void prim(){
int i,mark;
double tmp,sum;
for(i=1;i<=n;i++)
edge[i] = dis[1][i];
visit[1] = true;
sum = 0;
while(1){
tmp = INF;
mark = n+1;
for(i=1;i<=n;i++){
if(visit[i] == false && tmp > edge[i]){
tmp = edge[i];
mark = i;
}
}
if(mark==n+1) break;
sum += tmp;
visit[mark] = true;
for(i=1;i<=n;i++){
if(visit[i] == false && edge[i] > dis[mark][i])
edge[i] = dis[mark][i];
}
}
printf("%.2f/n",sum);
}
int main(){
input();
init();
prim();
}