HDOJ 1162 Eddy's picture(最小生成树)

来源:互联网 发布:靖江王城值得去吗 知乎 编辑:程序博客网 时间:2024/05/22 03:08


Eddy's picture




Problem Description
Eddy begins to like painting pictures recently ,he is sure of himself to become a painter.Every day Eddy draws pictures in his small room, and he usually puts out his newest pictures to let his friends appreciate. but the result it can be imagined, the friends are not interested in his picture.Eddy feels very puzzled,in order to change all friends 's view to his technical of painting pictures ,so Eddy creates a problem for the his friends of you.
Problem descriptions as follows: Given you some coordinates pionts on a drawing paper, every point links with the ink with the straight line, causes all points finally to link in the same place. How many distants does your duty discover the shortest length which the ink draws?
 

Input
The first line contains 0 < n <= 100, the number of point. For each point, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the point. 

Input contains multiple test cases. Process to the end of file.
 

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

Sample Input
31.0 1.02.0 2.02.0 4.0
 

Sample Output
3.41
题目大意:给出一些点,每两个点之间有一条连线,求最小生成树。

解题思路:建图 + Kruskal

代码如下:

#include <bits/stdc++.h>#include <iomanip>#define rank Rank//与命名空间某个rank函数冲突using namespace std;const int maxn = 105;const int maxm = 10005;struct Point{    double x,y;}point[maxn];struct Edge{    int from,to;    double dis;}edge[maxm];int cnt,n;int par[maxn],rank[maxn];void init(){    for(int i = 0;i < n;i++){        par[i] = i;        rank[i] = 0;    }    cnt = 0;}int find(int x){    return par[x] == x ? x : find(par[x]);}void unite(int x,int y){    x = find(x);    y = find(y);    if(x == y) return ;    if(rank[x] < rank[y])        par[x] = y;    else {        par[y] = x;        if(rank[x] == rank[y])            rank[x]++;    }}bool same(int x,int y){    return find(x) == find(y);}bool cmp(Edge a,Edge b){    return a.dis < b.dis;}double Kruskal(){    std::sort(edge,edge + cnt,cmp);    double res = 0;    for(int i = 0;i < cnt;i++){        Edge e = edge[i];        if(same(e.from,e.to)) continue;        unite(e.from,e.to);        res += e.dis;    }    return res;}double getLength(Point a,Point b){    return sqrt(pow(a.x - b.x,2.0) + pow(a.y - b.y,2.0));}int main(void){    while(cin >> n){        init();        for(int i = 0;i < n;i++){            cin >> point[i].x >> point[i].y;        }        for(int i = 0;i < n;i++){            for(int j = i + 1;j < n;j++){                edge[cnt].from = i;                edge[cnt].to = j;                edge[cnt++].dis = getLength(point[i],point[j]);            }        }        double ans = Kruskal();        cout << setiosflags(ios::fixed) << setprecision(2) << ans << endl;    }    return 0;}


0 0
原创粉丝点击