UVA 10369 - Arctic Network(最小生成树)

题目链接 https://cn.vjudge.net/problem/UVA-10369

【题意】
n个村庄的坐标已知,现在要架光纤使所有的村庄都能上网,但受光纤的参数d所限,每根光纤只能给距离不超过d的村庄之间连接。但是有s个信号机,信号机之间能无限畅连。考虑到光纤的价格和参数d有关,现在要确定最小的参数。 s <= 100 , s < n <= 500 , | x | , | y | <= 10000

【思路】
最好的方案当然是把s个信号机都用上,答案就是最小生成树中第s大的边的边权。

#include<bits/stdc++.h>
using namespace std;

const int maxn=505;

struct Edge{
    int from,to;
    double dist;
    Edge(int f,int t,double d):from(f),to(t),dist(d){}
    bool operator<(const Edge& e)const{
        return dist<e.dist;
    }
};

int n,s;
int x[maxn],y[maxn];
int par[maxn];
vector<Edge> edges;

int find(int x){ return x==par[x]?x:par[x]=find(par[x]); }

void kruscal(){
    sort(edges.begin(),edges.end());
    for(int i=0;i<n;++i) par[i]=i;
    int cnt=0;
    for(int i=0;i<edges.size();++i){
        Edge& e=edges[i];
        int x=find(e.from);
        int y=find(e.to);
        if(x!=y){
            par[x]=y;
            if(++cnt==n-s){
                printf("%.2lf\n",e.dist);
                return;
            }
        }
    }
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&s,&n);
        edges.clear();
        for(int i=0;i<n;++i) scanf("%d%d",&x[i],&y[i]);
        for(int i=0;i<n;++i){
            for(int j=i+1;j<n;++j){
                double d=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
                edges.push_back(Edge(i,j,d));
            }
        }
        kruscal();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiao_k666/article/details/82670281