链接:点击打开链接
题意:给出一个已连接的边,求将所有边连接起来的最短距离
代码:
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define maxx 99999999; double dis[200],a[200][200]; int sign[200],x[200],y[200],n,st,en; double sum=0; void prim(int v){ int i,j,u; double temp; for(i=1;i<=n;i++){ dis[i]=a[v][i]; sign[i]=0; } dis[v]=0;sign[v]=1; for(i=2;i<=n;i++){ temp=maxx; u=v; for(j=1;j<=n;j++) if(dis[j]<temp&&sign[j]==0){ temp=dis[j]; u=j; } sum+=temp; sign[u]=1; for(j=1;j<=n;j++){ if(a[u][j]<dis[j]&&sign[j]==0) dis[j]=a[u][j]; } } } using namespace std; int main(){ int i,j; while(cin>>n&&n){ cin>>st>>en; for(i=1;i<200;i++) for(j=1;j<200;j++) a[i][j]=maxx; for(i=1;i<=n;i++) cin>>x[i]>>y[i]; for(i=1;i<=n;i++) for(j=1;j<=n;j++) a[i][j]=a[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); sum=sqrt((x[st]-x[en])*(x[st]-x[en])+(y[st]-y[en])*(y[st]-y[en])); a[st][en]=a[en][st]=0; //就是将已连接的两个点距离设为0,再用prim算法求最小生成树 prim(1); printf("%.2lf\n",sum); } return 0; }