poj 2560 Freckles(並查集)

Freckles

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8749 Accepted: 4177
Description

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.
Input

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.
Output

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

3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output

3.41


給出一些座標點,求連通所有點所需最短路徑。
可以用最小生成樹kruskal算法。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 111
#define inf 0x3f3f3f3f
int p[N];
struct node{
    double x, y, z;
}nod[N],way[N*N];

bool cmp( node a, node b ){ return a.z < b.z; }
int fnd( int x ) { return p[x] = p[x] == x ? x : fnd( p[x] ); }
int main()
{
    //freopen( "in.txt", "r", stdin );
    int t, cnt = 1;
    double sum = 0;
    scanf( "%d", &t );
    for( int i = 1 ; i <= t ; i ++ ){
        scanf( "%lf%lf", &nod[i].x, &nod[i].y );
    }
    for( int i = 1 ; i <= t ; i ++ ){
        for( int j = 1 ; j < i ; j ++ ){
            way[cnt].x = i;
            way[cnt].y = j;
            way[cnt++].z = sqrt( (nod[i].x-nod[j].x)*(nod[i].x-nod[j].x)+(nod[i].y-nod[j].y)*(nod[i].y-nod[j].y));
        }
    }
    sort( way+1, way+cnt, cmp );///
    for( int i = 0 ; i <= t ; i ++ ) p[i] = i;
    for( int i = 1 ; i < cnt ; i ++ ){
        int u = fnd( way[i].x );
        int v = fnd( way[i].y );
        if( u != v ){
            p[u] = way[i].y;
            sum += way[i].z;
        }
    }
    printf( "%.2lf\n", sum );
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章