九度 题目1144:Freckles

题目描述:

    In an episode of the Dick Van Dyke show, little Richie connects the freckles on his Dad's back to form a picture of the Liberty Bell. Alas, one of the freckles turns out to be a scar, so his Ripley's engagement falls through. 
    Consider Dick's back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle. 

输入:

    The first line contains 0 < n <= 100, the number of freckles on Dick's back. For each freckle, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the freckle.

输出:

    Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.

样例输入:
3
1.0 1.0
2.0 2.0
2.0 4.0
样例输出:
3.41

题目简单翻译一下就是:输入n为节点数;然后下面n行是每个节点的坐标;然后输出是这n个节点的连通最短路径;

AC的代码如下:

#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
int fin[100];
struct node{//节点类,用来存储节点信息
    double x;
    double y;
}nod[100];

struct edge{//边的类,设置起点编号总是小于终点编号,避免了重复计算边
    int start;
    int end;
    double side;
}edg[5000];

double fun(node a, node b){//求边的距离长度
    double num = (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y);
    return sqrt(num);
}

bool cmp(edge e1, edge e2){//比较函数,用来将边的长度按照从小到大排序
    return e1.side < e2.side;
}

int find(int a){//并查集的运用
    if(fin[a] == a){
        return a;
    }
    return find(fin[a]);
}

void Merge(int a,int b){//并查集的运用
    a = find(a);
    b = find(b);
    fin[a] = fin[b];
}

int main(){
    int n;
    double a,b;
    while(scanf("%d",&n) != EOF){
        //初始化
        for(int i = 0; i < n; i++){
            scanf("%lf%lf",&a,&b);
            nod[i].x = a;
            nod[i].y = b;
            fin[i] = i;
        }
        int index = 0;
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                edg[index].start = i;
                edg[index].end = j;
                edg[index].side = fun(nod[i],nod[j]);
                index++;
            }
        }
        sort(edg, edg + index, cmp);//对边进行排序
        double sum = 0;//用来计算最短连通路径长度
        //开始选边,从小到大开始选,运用的是克鲁斯卡尔算法
        for(int i = 0; i < index; i++){
            int a = edg[i].start;
            int b = edg[i].end;
            if(find(a) != find(b)){
                Merge(a,b);
                sum = sum + edg[i].side;
            }
        }
        printf("%.2lf\n",sum);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值