P1265 highway construction Minimum spanning tree prim

answer

Eh it is a prim board questions

prim: point as the center, the nearest point from the tree to find each added to the tree

d [i] is the nearest recorded points to the vicinity of the current point i

memset NA filled array type double


Here Insert Picture Description


#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
bool vis[N];
double d[N];//d[i]记录的是当前点i到附近最近的点的距离
int n;
struct node{
    double x,y;
    void input(){
        scanf("%lf%lf",&x,&y);
    }
    double dis(const node& b){
        return sqrt((x-b.x)*(x-b.x)+(y-b.y)*(y-b.y));
    }
}a[N];

double prim(){
    for(int i=1;i<=n;i++) d[i]=1e9;//double类型 memset是无法适用的

    d[1]=0.0;
    double res=0.0;
    for (int i = 0; i < n; ++i) {
        int f=-1;
        for (int j = 1; j <= n; ++j) {
            if(!vis[j] && (f==-1 || d[j]<d[f]))
                f=j;
        }
        //if(i && dis[f]==INF) return INF; //不存在不成图的情况
        if(i)res+=d[f];
        vis[f]=1;
        for (int j = 1; j <= n; ++j) {
            if(!vis[j])
                d[j]=min(d[j],a[f].dis(a[j]));
        }
    }
    return res;
}
int main(){
    scanf("%d",&n);
    for (int i = 1; i <= n; ++i) {
        a[i].input();
    }
    printf("%.2f", prim());
    return 0;
}
Published 43 original articles · won praise 0 · Views 1255

Guess you like

Origin blog.csdn.net/Yubing792289314/article/details/104118875
Recommended