当前位置: 代码迷 >> 综合 >> 畅通工程再续//HDOJ-1875//kruskal
  详细解决方案

畅通工程再续//HDOJ-1875//kruskal

热度:55   发布时间:2024-01-10 06:53:11.0

畅通工程再续//HDOJ-1875//kruskal


题目

相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组RPRush对百岛湖的情况充分了解后,决定在符合条件的小岛间建上桥,所谓符合条件,就是2个小岛之间的距离不能小于10米,也不能大于1000米。当然,为了节省资金,只要求实现任意2个小岛之间有路通即可。其中桥的价格为 100元/米。
Input
输入包括多组数据。输入首先包括一个整数T(T <= 200),代表有T组数据。
每组数据首先是一个整数C(C <= 100),代表小岛的个数,接下来是C组坐标,代表每个小岛的坐标,这些坐标都是 0 <= x, y <= 1000的整数。
Output
每组输入数据输出一行,代表建桥的最小花费,结果保留一位小数。如果无法实现工程以达到全部畅通,输出”oh!”.
Sample Input
2
2
10 10
20 20
3
1 1
2 2
1000 1000
Sample Output
1414.2
oh!
链接:https://vjudge.net/contest/351234#problem/K

思路

典型求最小生成树,先记录好每个点的坐标,遍历所有点,两个点求距离。

代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>using namespace std;const double INF = 1e8;
int n,T,ans;
int root[200];struct node{
    int u,v;double cost;
}a[10100],b[10100];
double cal(node x,node y){
    double dis=sqrt((x.u-y.u)*(x.u-y.u)+(x.v-y.v)*(x.v-y.v));//计算距离return dis;
}
bool cmp(node x,node y){
    return x.cost<y.cost;
}
void init(){
                               //并查集初始化for(int i=0;i<n;i++){
    root[i]=i;}return;
}int findx(int x){
                         //查找操作if(root[x]==x) return x;elsereturn root[x]=findx(root[x]);
}/*bool same(int a,int b){return findx(a)==findx(b); }*/
int unite(int x,int y){
                     //合并操作x=findx(x);y=findx(y);if(x==y)return 0;if(x>y)root[x]=y;elseroot[y]=x;return 1;
}double kruskal(int k){
                      //kruskal算法求最小生成树sort(b,b+k,cmp);init();double sum=0.0;ans=0;for(int i=0;i<k;i++){
    node p = b[i];if(p.cost>=10&&p.cost<=1000&&unite(p.u,p.v)){
    //依题意去掉不符合的ans++;                                   //如不符合的太多ans不足n-1则说明不能全连sum+=p.cost;}if(ans==n-1) break;}return sum;
}
int main()
{
    cin>>T;while(T--){
    cin>>n;for(int i=0;i<n;i++){
    cin>>a[i].u>>a[i].v;              //记录每个坐标}int k=0;for(int i=0;i<n;i++){
    for(int j=0;j<i;j++){
                  //记录两个点对应的距离b[k].u=i;b[k].v=j;b[k].cost=cal(a[i],a[j]);k++;}}double sum=kruskal(k);if(ans==n-1)printf("%.1lf\n",sum*100);elseprintf("oh!\n");}return 0;
}

注意

并查集的初始化以及各类型的不同。