赞
踩
Case 3: 1.00
为在一条线段上找到一点,与给定的P点距离最小。很明显的凸性函数,用三分法来解决。dist函数即为求某点到P点的距离。注意精度问题。
- #include<iostream>
- #include<cstdio>
- #include<cmath>
- #define eps 1e-8
- using namespace std;
-
- typedef struct node
- {
- double x,y,z;
- }node;
- node l,r,p;
-
- double dist(node a,node b)
- {
- return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z));
- }
-
- int sgn(double a)
- {
- return (a>eps)-(a<-eps);
- }
-
- node getmid(node a,node b)
- {
- node mid;
- mid.x=(a.x+b.x)/2;
- mid.y=(a.y+b.y)/2;
- mid.z=(a.z+b.z)/2;
- return mid;
- }
-
- node search()
- {
- node mid,midmid;
- while(sgn(dist(l,r))>0)
- {
- mid=getmid(l,r);
- midmid=getmid(mid,r);
- if(dist(p,mid)<dist(p,midmid))
- r=midmid;
- else
- l=mid;
- }
- return r;
- }
-
- int main()
- {
- int t;node k;
- cin>>t;
- for(int i=1;i<=t;i++)
- {
- cin>>p.x>>p.y>>p.z;
- cin>>l.x>>l.y>>l.z;
- cin>>r.x>>r.y>>r.z;
- k=search();
- printf("Case %d: %.2lf\n",i,dist(k,p));
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。