前两天编程之美,有个题是这样的:二维坐标系上第一象限有一些点,让在x轴上找个点到所有点的距离和最小。因为这道题学习了三分搜索法。。
其实三分法原理非常简单,和二分法类似。。适用于这种情况:
在区间[L,R]中找两个三分点,也就是l=L+(R-L)/3和r=R-(R-L)/3,然后比较这两个点的y值大小。如果是求最大值的情况,如果y(l)<=y(r),说明最大值肯定在l右边,这时把区间变成[l,R],反之变成[L,r],直到L和R很接近为止。如果是求最小值的情况就反过来。
如果取值符合这样的凹凸曲线,就有可能是三分法做。三分法似乎往往和几何题有关系。。
Turn the corner
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1634 Accepted Submission(s): 610
Problem Description
Mr. West bought a new car! So he is travelling around the city.
One day he comes to a vertical corner. The street he is currently in has a width x, the street he wants to turn to has a width y. The car has a length l and a width d.
Can Mr. West go across the corner?
One day he comes to a vertical corner. The street he is currently in has a width x, the street he wants to turn to has a width y. The car has a length l and a width d.
Can Mr. West go across the corner?
![](http://acm.hdu.edu.cn/data/images/2438-1.jpg)
Input
Every line has four real numbers, x, y, l and w.
Proceed to the end of file.
Proceed to the end of file.
Output
If he can go across the corner, print "yes". Print "no" otherwise.
Sample Input
10 6 13.5 4 10 6 14.5 4
Sample Output
yes no
问车能不能转弯过去。
网上的图,太机智了:
算出上面那条边的方程,设P点为方程y=X的点,算出P的x坐标,取-x,角度a(下面那条边和x轴的夹角)在从0到pi/2的过程中,如果-x一直小于Y的话,就可以转过去。因为-x随角度增加是先增加后减小的,所以只要算出最大的时候是不是小于Y就可以判断,用三分法算出这个极值。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cstdlib>
#include<cmath>
#define INF 0x3f3f3f3f
#define MAXN 50010
#define MAXM 15
#define MAXNODE 30000
#define eps 1e-10
#define pi 4*atan(1)
#define pii pair<int,int>
using namespace std;
double X,Y,L,D;
double calc(double a){
return -(X-L*sin(a)-D/cos(a))/tan(a);
}
double tsearch(double L,double R){
double l,r,lv,rv;
while(R-L>eps){
l=L+(R-L)/3;
r=R-(R-L)/3;
lv=calc(l);
rv=calc(r);
if(lv<=rv) L=l;
else if(lv>rv) R=r;
}
return calc(L);
}
int main(){
freopen("in.txt","r",stdin);
while(scanf("%lf%lf%lf%lf",&X,&Y,&L,&D)!=EOF){
if(tsearch(0,pi/2)<=Y) printf("yes\n");
else printf("no\n");
}
return 0;
}