畅通工程再续 - 最小生成树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!

分析:多了限制条件,只需要在循环时加上限制条件,并设一个变量记录加入边的个数,当加入的边==n-1时说明可以

代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=105;
int n,cx[N],cy[N],pre[N];
struct proc{
    int from,to;
    double cost;
}edge[10010];

int cmp(proc a,proc b){
    return a.cost<b.cost;
}

int f(int x){
    if(x==pre[x])return x;
    pre[x]=f(pre[x]);
    return pre[x];
}


int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            scanf("%d%d",&cx[i],&cy[i]);
        }
        int k=0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                edge[k].from=i;
                edge[k].to=j;
                edge[k++].cost=sqrt((double)((cx[i]-cx[j])*(cx[i]-cx[j])+(cy[i]-cy[j])*(cy[i]-cy[j])));
            }
        }
        sort(edge,edge+k,cmp);
        int flag=0;
        for(int i=1;i<=n;i++)pre[i]=i;
        double ans=0;
        for(int i=1;i<=k;i++){
            int fx=f(edge[i].from);
            int fy=f(edge[i].to);
            if(edge[i].cost>=10&&edge[i].cost<=1000&&fx!=fy){
                pre[fx]=fy;
                ans+=edge[i].cost;
                flag++;
            }
            if(flag==m-1)break;
        }
        if(flag==n-1)printf("%.1f\n",ans*100);
        else printf("oh!\n");
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37579232/article/details/80230659
今日推荐