Problem B
Posted tansanity
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Problem B相关的知识,希望对你有一定的参考价值。
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.<br>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?<br>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. <br><br>Input contains multiple test cases. Process to the end of file.<br>
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. <br>
Sample Input
3 1.0 1.0 2.0 2.0 2.0 4.0
Sample Output
3.41
简单题意: Eddy喜欢作画,但是他的朋友却不能理解,所以,他在一张图上(空间直角坐标系)画出N个点,然后让你找出能连接所有点的连线的最短长度。 解题思路形成过程: 对于这个题目,理解是很容易的。给出点的坐标来,然后先求出各个点之间的距离,这就相当于带权无向图的权,然后的问题,不就是对这些点所构成的无向图做prim算法或者kruskal算法,求出最小生成树。所以思路很清晰。 感想: 大概是我对这两种算法的代码还不熟悉,上课刚听完,就开始着手这个题目。我最开始的做法是Kruskal算法解决问题,因为现在拥有各个点的坐标、距离,也就是图中的顶点和权,运用算法后,各种测试结果都正确,但是 WA。无奈转为prim算法,但是prim复杂程度一点不比kruskal低。所以,又出现错误。最后回归kruskal,看到别人是怎么运用的,最终解决问题。 AC代码; #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
struct Node
int x,y;
double cost;
g[5005];
int pre[105];
int find(int n)return n==pre[n]? n: find(pre[n]);
bool cmp(Node a,Node b)return a.cost < b.cost;
int main()
int n;
while(scanf("%d",&n) != EOF)
int k=0;
double sum=0;
double x[105],y[105];
for(int i = 1; i <= n; i++)scanf("%lf%lf",&x[i],&y[i]);
for(int i = 1;i <= n; i++)
for(int j = i+1; j <= n; j++)
g[k].x = i;
g[k].y = j;
g[k++].cost = sqrt(abs((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])));
for(int i = 1;i <= n; i++)pre[i] = i;
sort(g,g+k,cmp);
for(int i = 0; i < k; i++)
int x = find(g[i].x);
int y = find(g[i].y);
double z = g[i].cost;
if(x != y)
sum += z;
pre[x]=y;
printf("%.2f\\n",sum);
return 0;
以上是关于Problem B的主要内容,如果未能解决你的问题,请参考以下文章
CF1288B-Yet Another Meme Problem
2015浙工大校赛-Problem C: 三角—— 费马大定理+勾股数