九度 题目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);
    }
}

posted on 2017-06-14 11:57  ljbguanli  阅读(127)  评论(0编辑  收藏  举报