天天看點

九度 題目1144:Freckles

九度 題目1144:Freckles

原題OJ連結:http://ac.jobdu.com/problem.php?pid=1144

題目描述:

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
           

解題思路:

題目大意為平面上有若幹個點,我們需要用一些線段來将這些點連接配接起來使任意兩個點能夠通過一系列的線段相連,給出所有點的坐标,求一種連接配接方式使所有線段的長度和最小,求該長度和。

若将平面上的點抽象成圖上的點,将結點間直接相鄰的線段抽象成連結結點的邊,且權值為其長度,那麼類似于幾何最優值的問題轉化為圖論上的最小生成樹問題。但在開始求最小生成樹之前,必須建立該圖,得出所有的邊和相應的權值。

源代碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define MAX_N 105
using namespace std;

int Tree[MAX_N];

struct Node{
    double x,y;
} V[MAX_N];

struct Edge{
    int n1,n2;
    double cost;
} E[];

bool cmp(Edge a,Edge b){
    return a.cost<b.cost;
}

int findRoot(int x){
    if(Tree[x]==-) return x;
    else{
        int tmp=findRoot(Tree[x]);
        Tree[x]=tmp;
        return tmp;
    }
}

int main(){
    int n;
    while(cin>>n){
        memset(Tree,-,sizeof(Tree));
        for(int i=;i<n;i++){
            cin>>V[i].x>>V[i].y;
        }
        int k=;
        for(int i=;i<n;i++){
            for(int j=i+;j<n;j++){
                E[k].n1=i;
                E[k].n2=j;
                E[k].cost=sqrt((V[i].x-V[j].x)*(V[i].x-V[j].x)+
                               (V[i].y-V[j].y)*(V[i].y-V[j].y));
                k++;
            }
        }
        sort(E,E+k,cmp);
        double ans=;
        for(int i=;i<k;i++){
            int a=E[i].n1;
            int b=E[i].n2;
            a=findRoot(a);
            b=findRoot(b);
            if(a!=b){
                Tree[a]=b;
                ans=ans+E[i].cost;
            }
        }
        printf("%.2f\n",ans);
    }
    return ;
}