This is a simple problem. Given two triangles A and B, you should determine they are intersect, contain or disjoint. (Public edge or point are treated as intersect.)
Input
First line contains an integer T (1 ≤ T ≤ 10), represents there are T test cases.
For each test case: X1 Y1 X2 Y2 X3 Y3 X4 Y4 X5 Y5 X6 Y6. All the coordinate are integer. (X1,Y1) , (X2,Y2), (X3,Y3) forms triangles A ; (X4,Y4) , (X5,Y5), (X6,Y6) forms triangles B.
-10000<=All the coordinate <=10000
Output
For each test case, output “intersect”, “contain” or “disjoint”.
Sample Input
2 0 0 0 1 1 0 10 10 9 9 9 10 0 0 1 1 1 0 0 0 1 1 0 1
Sample Output
disjoint intersect
思路:给定平面上一点p(x0,y0),判断该点是否在三角形ABC中,三角形顶点坐标分别为A(xa,xb),B(xb,yb),C(xc,yc)。可以使用面积法来判断,方法如下:其中S(A,B,C)表示三角形ABC的面积。
1、 若abs( S(A,B,C) ) = abs( S(P,B,C) ) + abs( S(A,P,C) ) + abs( S(A,B,P) ) ,则P在三角形ABC的内部或边上;如果还有abs( S(P,B,C) )、abs( S(A,P,C) ) 和abs( S(A,B,P) )全都大于0,则说明P在三角形ABC的内部,否则P在三角形ABC的边上,具体为:S(P,B,C)为0,则说明P在BC边上,S(A,P,C)为0,则说明P在AC边上,S(A,B,P)为0,则说明P在AB边上;
2、 若abs( S(A,B,C) ) < abs( S(P,B,C) ) + abs( S(A,P,C) ) + abs( S(A,B,P) ) ,则P在三角形ABC的外部;
3、 对abs( S(A,B,C) ) > abs( S(P,B,C) ) + abs( S(A,P,C) ) + abs( S(A,B,P) ) 情况在理论上是不存在的
此处又引出另一个问题,如何求平面中三角形的面积?这个可以使用叉乘法来实现,即S(A,B,C)为向量AB叉乘AC所得向量模的1/2,再对该值求绝对值就是三角形ABC的面积。
#include
#include
#include
using namespace std;
#define eps 0.0001
struct point
{
int x,y;
point(int a,int b)
{
x=a,y=b;
}
};
//计算三角形面积
float GetTriangleSquar(const point p1,const point p2,const point p3)
{
point p12(0,0);
point p23(0,0);
p12.x=p2.x-p1.x;
p12.y=p2.y-p1.y;
p23.x=p3.x-p2.x;
p23.y=p3.y-p2.y;
return fabs(p12.x*p23.y-p12.y*p23.x)/2.0f;
}
//给定一点是否在三角形内或边上。
bool IsInTriangle(const point A,const point B,const point C,const point D)
{
float Sabc,Sadb,Sbdc,Sadc;
Sabc=GetTriangleSquar(A,B,C);
Sadb=GetTriangleSquar(A,D,B);
Sbdc=GetTriangleSquar(B,D,C);
Sadc=GetTriangleSquar(A,D,C);
float SumSquar=Sadb+Sbdc+Sadc;
if((-eps<(Sabc-SumSquar))&&((Sabc-SumSquar)>T;
while(T--)
{
int x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6;
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4>>x5>>y5>>x6>>y6;
point a1(x1,y1),b1(x2,y2),c1(x3,y3);
point a2(x4,y4),b2(x5,y5),c2(x6,y6);
bool f=0;
int p=0;
while(1)
{
p=0;
if(IsInTriangle(a1,b1,c1,a2))
{
p++;
}
if(IsInTriangle(a1,b1,c1,b2))
{
p++;
}
if(IsInTriangle(a1,b1,c1,c2))
{
p++;
}
if(p==3)
{
cout<<"contain"<