题解:P17016 [GESP202606 八级] 线网建设

· · 题解

本题数据范围 1 \le n \le 500 ,因此我们可以想到使用最小生成树中的 Kruskal 算法来解决。
因此本题套 Kruskal 的模板即可。
但是本题有几个注意事项:

代码如下:

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+5;
struct Pos{
    int a;
    int b;
    double c;
};
int p[maxn];
int sz[maxn];
int getp(int x){
    if(x==p[x]){
        return x;
    }
    return p[x]=getp(p[x]);
}
bool lnk(int x,int y){
    if(getp(x)==getp(y)){
        return 0;
    }
    int xx=getp(x);
    int yy=getp(y);
    if(sz[xx]>sz[yy]){
        swap(xx,yy);
    }
    p[xx]=yy;
    sz[yy]+=sz[xx];
    return 1;
}
bool bijiao(Pos a,Pos b){
    return a.c<b.c;
}
double juli(int a,int b,int c,int d){
    return 1.0*sqrt(1.0*((b-a)*(b-a)+(d-c)*(d-c)));
}
int main(){
    int a,b;
    cin>>a>>b;
    if(a==1){
        cout<<"0.00"<<endl;
        return 0;
    }
    int x[maxn];
    int y[maxn];
    for(int i=1;i<=a;i++){
        cin>>x[i];
        cin>>y[i];
        p[i]=i;
        sz[i]=1;
    }
    vector<Pos> ii;
    int hee=0;
    for(int i=1;i<=a;i++){
        for(int j=i+1;j<=a;j++){
            if(juli(x[i],x[j],y[i],y[j])<=b){
                ii.push_back({i,j,juli(x[i],x[j],y[i],y[j])});
                hee++;
            }
        }
    }
    sort(ii.begin(),ii.end(),bijiao);
    double he=0;
    int he2=0;
    for(int i=0;i<hee;i++){
        if(lnk(ii[i].a,ii[i].b)){
            he+=ii[i].c;
            he2++;
            if(he2==a-1){
                cout<<fixed<<setprecision(2)<<he;
                return 0;
            }
        }
    }
    cout<<"Impossible";
}