-
题目描述:
-
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
-
来源:
-
2009年北京大学计算机研究生机试真题
#include<iostream> #include <algorithm> #include <cstdio> #include <stdlib.h> #include <math.h> using namespace std; int Tree[101]; class road { public: double a; double b; double value; bool operator < (const road &B) const { return value < B.value; } }Edge[5050]; void initTree() { for(int i = 0; i<101; i++) { Tree[i] = -1; } } int FindRoot(int x) { if(-1 == Tree[x]) return x; int tmp = x; while(-1 != Tree[x]) { x = Tree[x]; } int re = x; while(-1 != Tree[tmp]) { x = Tree[tmp]; Tree[tmp] = re; tmp = x; } return re; } class point { public: double a; double b; double Getvalue(point B) { double tmp = (a-B.a)*(a-B.a) + (b-B.b)*(b-B.b); return sqrt(tmp); } }P[101]; int main() { int a,b,n,i,j; while(cin>>n) { initTree(); for(i=1; i<=n ; i++) { cin>>P[i].a>>P[i].b; } int ans = 0; for(i=1; i<n; i++) { for(j=i+1; j<=n; j++) { Edge[ans].a = i; Edge[ans].b = j; Edge[ans].value = P[i].Getvalue(P[j]);//计算了n(n-1)/2条边的权值 ans++; } } sort(Edge, Edge+ans); double value = 0; for(i=0; i<ans; i++) { a = FindRoot(Edge[i].a); b = FindRoot(Edge[i].b); if(a != b) { value += Edge[i].value; Tree[a] = b; } } printf("%.2f\n",value); } }
本文通过一个有趣的背景故事引入了最小生成树问题,并提供了一种有效的解决方案。文章详细描述了一个算法,该算法能够找到连接所有点所需的最短线段总长度,从而解决了一个经典的图论问题。

1124

被折叠的 条评论
为什么被折叠?



