Los P1265 Valley highway construction minimum spanning tree
answer:
We need to build a complete graph , the number of edges may be large , so the use of prim algorithm is better.
code show as below:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<cmath>
#include<queue>
#include<cstring>
#include<vector>
#include<map>
#define MAX 5005
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
int n;//n个结点
int visit[MAX];
double dis[MAX];
struct node{
ll x,y;
};
vector<node> vec;
void prim(){//prim算法
for(int i=0;i<MAX;i++){
visit[i]=0;
dis[i]=INF;
}
dis[1]=0;
for(int i=0;i<=n;i++){
int minl=INF,u=-1;
for(int j=1;j<=n;j++){
if(visit[j]==0&&dis[j]<minl){
minl=dis[j];
u=j;
}
}
if(u==-1) break;
visit[u]=1;
node t1=vec[u];
for(int v=1;v<=n;v++){
node t2=vec[v];
double tmp=sqrt((t1.x-t2.x)*(t1.x-t2.x)+(t1.y-t2.y)*(t1.y-t2.y));
if(visit[v]==0&&tmp<dis[v]){
dis[v]=tmp;
}
}
}
}
int main(){
scanf("%d",&n);
vec.resize(n+1);
for(int i=1;i<=n;i++){
scanf("%lld%lld",&vec[i].x,&vec[i].y);
}
prim();
double ans=0.0;
for(int i=1;i<=n;i++){
ans+=dis[i];
}
printf("%.2f",ans);
return 0;
}