码迷,mamicode.com
首页 > 其他好文 > 详细

K - 畅通工程再续

时间:2020-01-21 21:29:53      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:mod   main   问题   oid   条件   define   find   include   道路   

K - 畅通工程再续

相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现。现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全畅通!经过考察小组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!

题目描述:

给出各小岛的坐标。在c各小岛上建桥使道路连通。2个小岛之间的距离不能小于10米,也不能大于1000米。求建桥最低价格(桥的价格为100元/米)。

分析:

给出坐标,可以求出任意2点的距离,就可以转换成求最小生成树。使用kruskal算法,注意下判断是否符合10米到1000米的条件,符合才加入到要建的桥中。再纪录一下全部符合的桥一共有多少条,如果小于c-1条就不能实现工程了。(生成树的有c-1条边)

代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#define min(x,y) x<y?x:y;
#define INF 1000000
using namespace std;
struct point
{
    int x;
    int y;
}p[106];
struct edge
{
    int u;
    int v;
    double d;
}e[100006];
bool used[106];
int cost[106][106];
int parent[106];
int Rank[106];
int find(int x)
{
    if(x==parent[x]) return x;
    return find(parent[x]);
}
void Union(int x,int y)
{
    int xr=find(x);
    int yr=find(y);
    if(Rank[xr]==Rank[yr])
    {
        parent[xr]=yr;
        Rank[yr]++;
    }
    else if(Rank[xr]<Rank[yr])
    {
        parent[xr]=yr;
    }
    else
    {
        parent[yr]=xr;
    }
}
bool tong(int x,int y)
{
    return find(x)==find(y);
 } 
double cald(point a,point b)
{
    return sqrt((a.x-b.x)*(a.x-b.x)*1.0+(a.y-b.y)*(a.y-b.y)*1.0);
}
double cmp(edge a,edge b)
{
    return a.d<b.d;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int c;
        double ans=0;
        scanf("%d",&c);
        for(int i=1;i<=c;i++)
        {
            scanf("%d%d",&p[i].x,&p[i].y);
            parent[i]=i;
        }
        int posi=0;
        for(int i=1;i<=c;i++)
        {
            for(int j=i+1;j<=c;j++)
            {
                double num=cald(p[i],p[j]);
                e[posi].u=i;
                e[posi].v=j;
                e[posi++].d=num;
            }
        }
        sort(e,e+c*(c-1)/2,cmp);
        int line=0;
        for(int i=0;i<c*(c-1)/2;i++)
        {
            if(!tong(e[i].u,e[i].v)&&e[i].d>=10&&e[i].d<=1000)
            {
                Union(e[i].u,e[i].v);
                ans+=e[i].d;
          line++;
         }
       }
    if(line==c-1)
    printf("%.1f\n",ans*100);
    else printf("oh!\n");
    }
  return 0;
}
?

 

 

K - 畅通工程再续

标签:mod   main   问题   oid   条件   define   find   include   道路   

原文地址:https://www.cnblogs.com/studyshare777/p/12222845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!