1264 线段相交
给出平面上两条线段的两个端点,判断这两条线段是否相交(有一个公共点或有部分重合认为相交)。 如果相交,输出"Yes",否则输出"No"。
这道题刘汝佳的的训练指南上有有讲,其中判断端点是否在线段上需要判断四次
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
const double eps=1e-10;
using namespace std;
struct Point
{
double x,y;
Point(double x=0,double y=0):x(x),y(y){}
};
typedef Point Vector;
double Cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
Vector operator-(Point A,Point B)
{
return Vector(A.x-B.x,A.y-B.y);
}
double Dot(Vector A,Vector B)
{
return A.x*B.x+A.y*B.y;
}
double Length(Vector A)
{
return sqrt(Dot(A,A));
}
double Distance(Point P,Point A,Point B)
{
Vector v1=B-A,v2=P-A;
return fabs(Cross(v1,v2))/Length(v1);
}
int dcmp(double x)
{
if(fabs(x)<eps)
return 0;
else
return x<0?-1:1;
}
bool Segment(Point a1,Point a2,Point b1,Point b2)
{
double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1),
c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);
return dcmp(c1)*dcmp(c2)<0&&dcmp(c3)*dcmp(c4)<0;
}
bool onSeg(Point p,Point a1,Point a2)
{
return dcmp(Cross(a1-p,a2-p))==0&&dcmp(Dot(a1-p,a2-p))<0;
}
int main()
{
int T;
double xc,yc,R;
double x[4],y[4];
scanf("%d",&T);
while(T--)
{
for(int i=0;i<4;i++)
scanf("%lf %lf",&x[i],&y[i]);
if((x[0]==x[2]&&y[0]==y[2])||(x[0]==x[3]&&y[0]==y[3])||(x[1]==x[2]&&y[1]==y[2])||x[1]==x[3]&&y[1]==y[3])
{
printf("Yes\n");
continue;
}
Point a1(x[0],y[0]);
Point a2(x[1],y[1]);
Point a3(x[2],y[2]);
Point a4(x[3],y[3]);
if(Segment(a1,a2,a3,a4)||onSeg(a1,a3,a4)||onSeg(a2,a3,a4)||onSeg(a3,a1,a2)||onSeg(a4,a1,a2))
printf("Yes\n");
else
printf("No\n");
}
return 0;
}