TOJ 2371 Freckles 最小生成树 prim

た 入场券 2022-05-19 13:27 193阅读 0赞

2371: Freckles

描述

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

prim模板题。给n个点,问最短多少距离可以把他们都连起来。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<math.h>
  4. #include<iostream>
  5. #include<string>
  6. #include<algorithm>
  7. #include<map>
  8. #include<set>
  9. #include<queue>
  10. #include<vector>
  11. using namespace std;
  12. #define inf 0x3f3f3f3f
  13. #define LL long long
  14. int n;
  15. double graph[101][101];
  16. int vis[101];
  17. double prim()
  18. {
  19. memset(vis,0,sizeof vis);
  20. double ans=0,low[1005];
  21. int pos=0;
  22. vis[0]=1;
  23. for(int i=0;i<n;i++)
  24. low[i]=graph[pos][i];
  25. for(int i=1;i<n;i++)
  26. {
  27. double min=inf;
  28. for(int j=0;j<n;j++)
  29. {
  30. if(!vis[j]&&min>low[j])
  31. {
  32. min=low[j];
  33. pos=j;
  34. }
  35. }
  36. vis[pos]=1;
  37. ans+=min;
  38. for(int k=1;k<=n;k++)
  39. {
  40. if(!vis[k]&&low[k]>graph[pos][k])
  41. low[k]=graph[pos][k];
  42. }
  43. }
  44. return ans;
  45. }
  46. int main()
  47. {
  48. int i,j;
  49. double x[105],y[105];
  50. scanf("%d", &n);
  51. memset(graph,0,sizeof graph);
  52. for(i=0;i<n;i++)
  53. scanf("%lf%lf",&x[i],&y[i]);
  54. for(i=0;i<n;i++)
  55. {
  56. for(j=i+1;j<n;j++)
  57. graph[i][j]=graph[j][i]=sqrt((x[i]- x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i] - y[j]));
  58. }
  59. printf("%.2lf\n",prim());
  60. }

发表评论

表情:
评论列表 (有 0 条评论,193人围观)

还没有评论,来说两句吧...

相关阅读

    相关 1078 生成 prim

    题目描述 Description 农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。 约翰已经给他的农场安排了一

    相关 生成-Prim算法

    最小生成树的目的是使一个图的节点到其他各个节点的距离最短。产生的树成为最小生成树。 最小生成树算法分为普利姆(Prim)算法与克鲁斯卡尔(Kruskal)算法来解决。

    相关 prim算法--生成

    首先我们在这里先介绍一下prim算法,我记得大学数据结构先讲完最小生成树,再讲最短路径,也是考研必考问题。 prim算法在加权连通图里面寻找全局最小的生成树。是一个贪心算法。