给出平面上两条线段的两个端点,判断这两条线段是否相交(有一个公共点或有部分重合认为相交)。 如果相交,输出"Yes",否则输出"No"。
Input
第1行:一个数T,表示输入的测试数量(1 <= T <= 1000)
第2 - T + 1行:每行8个数,x1,y1,x2,y2,x3,y3,x4,y4。(-10^8 <= xi, yi <= 10^8)
(直线1的两个端点为x1,y1 | x2, y2,直线2的两个端点为x3,y3 | x4, y4)
Output
输出共T行,如果相交输出"Yes",否则输出"No"。Sample Input
2 1 2 2 1 0 0 2 2 -1 1 1 1 0 0 1 -1
Sample Output
Yes No
运用斜率判断两点是否在直线的上下方
AC代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
int flag;
double x1,y1,x2,y2,x3,y3,x4,y4;
double k,w1,w2,t1,t2;
scanf("%d",&t);
while(t--)
{
flag = 0;
scanf("%lf %lf %lf %lf %lf %lf %lf %lf",&x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
if(x1 - x2 == 0) //斜率不存在
{
if((x3>=x1 && x4<=x1)||(x3<=x1 && x4>=x1))
flag++;
}
else //存在
{
t1 = (x3 - x2);
t2 = (x4 - x2);
k = (double)(y2 - y1)/(x2 - x1);
w1 = k * t1 + y2;
w2 = k * t2 + y2;
if((w1<=y3 && w2>=y4)||(w1>=y3 && w2<=y4))
flag++;
}
if(x3 - x4 == 0)
{
if((x1>=x3 && x2<=x3)||(x1<=x3 && x2>=x3))
flag++;
}
else
{
t1 = (x1 - x3);
t2 = (x2 - x3);
k = (y3 - y4)/(x3 - x4);
w1 = k*t1 + y3;
w2 = k*t2 + y3;
if((w1<=y1 && w2>=y2)||(w1>=y1 && w2<=y2))
flag++;
}
if(flag == 2)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}