Description
Two star-crossed lovers want to meet. The two lovers are standing at distinct points in the plane (but then again, aren’t we all?). They can travel freely except that there is a single wall which cannot be crossed. The wall is a line segment which is parallel to either the x or y axis. Each lover can move 1 unit in 1 second. How long will it take them to be together if they both choose the best path?
Input
Input for each test case will consist of two lines each containing four integers. The first two integers will specify the x and y coordinates of the first lover; the next two integers will specify the x and y coordinates of the second lover. The next four integers will specify the start and end points of the wall. Furthermore, in all cases both lovers will not be on the (infinite) line containing the wall —that is, the wall extended in both directions. All coordinates will be positive and less than or equal to 10000 and neither lover will start on the wall. The input will be terminated by a line containing four zeroes.
Output
For each test case, output the minimum time in seconds for the two lovers to meet. Print the answer to exactly 3 decimal places, using the output format shown in the example.
Case 1: 1.000 Case 2: 1.414计算机几何关键是判断线段是否相交。自己分情况写的代码有点长。orz
#include<math.h>
using namespace std;
struct point{
double x;
double y;
};
point a,b,c,d;
double fan(double x,double y)
{
return x>y?x:y;
}
double fin(double c,double d)
{
return c<d?c:d;
}
double cnt(point a,point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
bool is(point a,point b,point c,point d)
{
if(a.x==b.x&&c.x==d.x)
{
return false;
}
if(a.x==b.x&&c.x!=d.x)
{
double m1=a.x;
double m2=(a.x-c.x)*(d.y-c.y)/(d.x-c.x)+c.y;
if(m1<=fan(a.x,b.x)&&m1>=fin(a.x,b.x)&&m2>=fin(a.y,b.y)&&m2<=fan(a.y,b.y)&&m1<=fan(c.x,d.x)&&m1>=fin(c.x,d.x)&&m2>=fin(c.y,d.y)&&m2<=fan(c.y,d.y)) return true;
}
if(c.x==d.x&&a.x!=b.x)
{
double m1=c.x;
double m2=a.y+(b.y-a.y)*(c.x-a.x)/(b.x-a.x);
if(m1<=fan(a.x,b.x)&&m1>=fin(a.x,b.x)&&m2>=fin(a.y,b.y)&&m2<=fan(a.y,b.y)&&m1<=fan(c.x,d.x)&&m1>=fin(c.x,d.x)&&m2>=fin(c.y,d.y)&&m2<=fan(c.y,d.y)) return true;
}
double k1=(b.y-a.y)/(b.x-a.x);
double k2=(d.y-c.y)/(d.x-c.x);
double m1,m2,x,y;
if(k1==k2) return false;
else
{
m1=a.y-k1*a.x;
m2=c.y-k2*c.x;
x=(m1-m2)/(k2-k1);
y=k1*x+m1;
if(x<=fan(a.x,b.x)&&x>=fin(a.x,b.x)&&y>=fin(a.y,b.y)&&y<=fan(a.y,b.y)&&x<=fan(c.x,d.x)&&x>=fin(c.x,d.x)&&y>=fin(c.y,d.y)&&y<=fan(c.y,d.y)) return true;
}
return false;
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int ca=0;
cout.precision(3);
while(cin>>a.x>>a.y>>b.x>>b.y)
{
ca++;
if(a.x==0&&a.y==0&&b.x==0&&b.y==0) break;
cin>>c.x>>c.y>>d.x>>d.y;
cout<<"Case "<<ca<<": ";
if(is(a,b,c,d)==1) cout<<fixed<<fin((cnt(a,c)+cnt(b,c))/2,(cnt(a,d)+cnt(b,d))/2)<<endl;
else cout<<fixed<<cnt(a,b)/2<<endl;
}
return 0;
}