1. 程式人生 > >無線通訊網(先存)

無線通訊網(先存)

#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
void read(int &n){
    int num=0,w=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-') w=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        num=num*10+ch-'0';
        ch=getchar();
    }
    n=num*w;
}
const int maxn=1000005;
int s,p; 
struct point{int x,y;}po[maxn];
struct node{
    int u,v;double w;
    bool operator < (const node &x) const{return w<x.w;}
}e[maxn];
int newp=0,fa[maxn];
double getdist(point a,point b){return sqrt(pow((double)a.x-(double)b.x,2)+pow((double)a.y-(double)b.y,2));}//get distance
int dofind(int v){return fa[v]==v?v:fa[v]=dofind(fa[v]);}
void dounion(int v1,int v2){fa[dofind(v1)]=dofind(v2);}
double Kruskal(){
    for(int i=1;i<=p;i++) fa[i]=i;
    sort(e+1,e+1+newp);
    double cnt=0,value=0;
    for(int i=1;cnt<p-s;i++){
        if(dofind(e[i].u)!=dofind(e[i].v)){
            dounion(e[i].u,e[i].v);
            value=e[i].w;
            cnt++;
        }
    }
    return value;
}
void init(){
    read(s);read(p);
    for(int i=1;i<=p;i++){
        int x,y;read(x);read(y);
        po[++newp]=(point){x,y};
    }
    newp=0;
    for(int i=1;i<=p;i++)
        for(int j=i+1;j<=p;j++)
            e[++newp]=(node){i,j,getdist(po[i],po[j])};
}
int main(){
    init();
    printf("%.2lf",Kruskal());
    return 0;
}