题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/69b1230a0e6b3ccfbb5d82b1dd3ec26e.png#pic_center)
法一:快速排斥+跨立试验
#include<stdio.h>
#include<math.h>
typedef struct point{
double x,y;
}Point;
typedef struct vector{
double x,y;
}Vector;
typedef struct{
double xmax,xmin;
double ymax,ymin;
}MBR;
double Max(double x,double y){
return x>y?x:y;
}
double Min(double x,double y){
return x<y?x:y;
}
Vector VectorConstruct(Point A, Point B) {
Vector v;
v.x = B.x - A.x;
v.y = B.y - A.y;
return v;
}
double CrossProduct(Vector a, Vector b) {
return a.x * b.y - a.y * b.x;
}
MBR MbrConstruct(Point A, Point B) {
MBR m;
if(A.x > B.x){
m.xmax = A.x;
m.xmin = B.x;
}
else{
m.xmax = B.x;
m.xmin = A.x;
}
if(A.y > B.y){
m.ymax = A.y;
m.ymin = B.y;
}
else{
m.ymax = B.y;
m.ymin = A.y;
}
return m;
}
int MbrOverlap(MBR m1, MBR m2) {
double xmin, xmax, ymin, ymax;
xmin = Max(m1.xmin, m2.xmin);
xmax = Min(m1.xmax, m2.xmax);
ymin = Max(m1.ymin, m2.ymin);
ymax = Min(m1.ymax, m2.ymax);
return (xmax >= xmin && ymax >= ymin) ? 1 : 0;
}
int SegmentIntersection(Point A, Point B, Point C, Point D) {
MBR m1,m2;
Vector CA,CB,CD,AC,AD,AB;
m1 = MbrConstruct(A, B);
m2 = MbrConstruct(C, D);
if(MbrOverlap(m1, m2) == 0)
return 0;
CA = VectorConstruct(C, A);
CB = VectorConstruct(C, B);
CD = VectorConstruct(C, D);
AC = VectorConstruct(A, C);
AD = VectorConstruct(A, D);
AB = VectorConstruct(A, B);
if (CrossProduct(CA, CD) * CrossProduct(CB, CD) <= 0 && CrossProduct(AC, AB) * CrossProduct(AD, AB) <= 0)
return 1;
else
return 0;
}
void main(){
int tag;
Point A,B,C,D;
A.x=1,A.y=2;
B.x=3,B.y=4;
C.x=1,C.y=3;
D.x=4,D.y=1;
tag=SegmentIntersection(A,B,C,D);
if(tag)
printf("两直线相交\n");
else
printf("两直线不相交\n");
}
法二:凸多边形
#include<stdio.h>
#include<math.h>
typedef struct point{
double x,y;
}Point;
typedef struct vector{
double x,y;
}Vector;
Vector VectorConstruct(Point A, Point B) {
Vector v;
v.x = B.x - A.x;
v.y = B.y - A.y;
return v;
}
double CrossProduct(Vector a, Vector b) {
return a.x * b.y - a.y * b.x;
}
int SegmentIntersection2(Point A, Point B, Point C, Point D) {
double c[4];
int f1=0, f2=0;
int i;
Vector AC = VectorConstruct(A, C);
Vector CB = VectorConstruct(C, B);
Vector BD = VectorConstruct(B, D);
Vector DA = VectorConstruct(D, A);
c[0] = CrossProduct(AC, CB);
c[1] = CrossProduct(CB, BD);
c[2] = CrossProduct(BD, DA);
c[3] = CrossProduct(DA, AC);
for(i=0; i<4; i++){
if(c[i] > 0)
f1++;
if(c[i] < 0)
f2++;
}
if (f1>0 && f2>0)
return 0;
else
return 1;
}
void main(){
int tag;
Point A,B,C,D;
A.x=1,A.y=2;
B.x=3,B.y=4;
C.x=1,C.y=3;
D.x=4,D.y=1;
tag=SegmentIntersection2(A,B,C,D);
if(tag)
printf("两直线相交\n");
else
printf("两直线不相交\n");
}