您的位置:首页 > 其它

BUAA 1033 (三分枚举计算 点到线段的最短距离)

2017-04-22 22:08 323 查看
[align=center]Easy Problem
[/align]

[align=center]时间限制:1000 ms  |  内存限制:65536 KB
[/align]
描述

In this problem, you're to calculate the distance between a point P(xp, yp, zp) and a segment (分段、线段)(x1, y1, z1) and(x2, y2, z2), in a 3D space, i.e. the minimal distance
from P to any point Q(xq, yq, zq) on the segment (a segment is part of a line).

输入

The first line contains a single integer T (1 ≤ T ≤ 1000), the number of test cases. Each test case is a single line containing 9 integers xp, yp, zp, x1, y1, z1, x2, y2, z2. These integers are all in [-1000,1000].

输出

For each test case, print the case number and the minimal distance, to two decimal places.

样例输入

3

0 0 0 0 1 0 1 1 0

1 0 0 1 0 1 1 1 0

-1 -1 -1 0 1 0 -1 0 -1

样例输出

Case 1: 1.00

Case 2: 0.71

Case 3: 1.00

思路

题目要求一点到一条线段上的最短距离,结果精确到小数点后两位

可以发现点到线段上一点的距离最短时,对于该点两边的点,距离都是逐渐增大的,也就是距离函数是单峰的,于是考虑三分枚举

控制精度标准,进行三分

三分模板

double calculate(type a)
{
//根据题目进行计算
}

void solve(void)
{
double left,right;
double mid,midmid;
double mid_value,midmid_value;
left=MIN;
right=MAX;
while(right-left>eps)
{
mid=(left+right)/2;
midmid=(mid+right)/2;
mid_value=calculate(mid);
midmid_value=calculate(midmid);
if(mid_value>=midmid_value) left=mid;//以极小值为例
else right=midmid;
}
//处理结果left(或right)
}


代码示例

#include<iostream>
#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
#define eps 1e-8
struct point{//点结构
double x,y,z;
};

double dist(point p1,point p2){//计算两点间距离
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)+(p1.z-p2.z)*(p1.z-p2.z));
}

int main()
{
int T,Count=0;
point p,l,r,p1,p2;
double d1,d2;
scanf("%d",&T);
while(T--)
{
scanf("%lf%lf%lf",&p.x,&p.y,&p.z);
scanf("%lf%lf%lf",&l.x,&l.y,&l.z);
scanf("%lf%lf%lf",&r.x,&r.y,&r.z);
while(dist(l,r)>eps)//不停缩短范围
{
p1.x=(l.x+r.x)/2.0;
p1.y=(l.y+r.y)/2.0;
p1.z=(l.z+r.z)/2.0;

p2.x=(p1.x+r.x)/2.0;
p2.y=(p1.y+r.y)/2.0;
p2.z=(p1.z+r.z)/2.0;
d1=dist(p1,p);
d2=dist(p2,p);
if(d1<=d2) r=p2;
else l=p1;
}
printf("Case %d: %.2lf\n",++Count,dist(p,r));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: