九度 OJ 题目1144:Freckles (kruskal算法 最小生成树)

来源:互联网 发布:东华云计算有限公司 编辑:程序博客网 时间:2024/06/05 20:06
题目描述:

    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.

样例输入:
31.0 1.02.0 2.02.0 4.0
样例输出:
3.41
/*使用kruskal算法,由输入的点先生成一张完全图,再找到最小生成树*/#include <stdio.h>#include<math.h>#include<algorithm>using namespace std;#define N 101double Tree[N];int findRoot(int x) {    if(Tree[x] == -1) return x;    else {        int tmp = findRoot(Tree[x]);        Tree[x] = tmp;        return tmp;    }}struct Edge{    int a, b;     //此处只是抽象出来的点(不同的整数代表不同的点),不要误认为要使用Point来定义a、b    double weight;  //权值    //重载<   为了使用sort()进行按权重由小到大的排序    bool operator < (const Edge &E) const {        return weight < E.weight;    }};//该结构的存在只是为了接受坐标参数,并计算两点之间的距离struct Point{    double x, y;    //点的两个坐标    //计算两点距离    double getDistance(Point A) {        double tmp = (x-A.x) * (x-A.x) + (y-A.y) * (y-A.y);        return sqrt(tmp);    }};Edge e[6000];Point p[101];int main(){    int n;    while(scanf("%d", &n) != EOF) {        //录入点坐标        for(int i=1;i<=n;i++) {            scanf("%lf%lf", &p[i].x,&p[i].y);        }        int size = 0;           //边的总数n*(n-1)/2        for(int i=1;i<=n;i++) {            for(int j=i+1;j<=n;j++) {                //将所有点两两相连产生的边存到e[]中                e[size].a = i;                e[size].b = j;                e[size].weight = p[i].getDistance(p[j]);                size++;            }        }        sort(e, e+n*(n-1)/2);   //按权值由小到大进行排序        //初始化Tree[]        for(int i=0;i<N;i++){            Tree[i] = -1;        }        double sum = 0;    //记录最小生成树的权值        //边数组中查找最小生成树        for(int i=0;i<n*(n-1)/2;i++) {            int a = findRoot(e[i].a);            int b = findRoot(e[i].b);            if(a != b) {                Tree[a] = b;                sum += e[i].weight;            }       }       printf("%.2lf\n", sum);    }    return 0;}

0 0
原创粉丝点击