Urban Design (mathematical vector, use cross product to judge whether the straight line intersects the line segment)

Insert picture description hereInsert picture description hereInsert picture description hereInsert picture description hereInsert picture description here
In fact, this question is easier to write if you understand the meaning of the question clearly;
I started to understand the meaning of the question incorrectly ; I understood it as whether the area passed by the line segment is the same or different, so I made a mistake at the beginning, and there is no idea; Later, I discovered this thing after supplementing the question:
Insert picture description here
here they refer to the area where the two points are located.
So this question can be found in this question:
Insert picture description here
when the line segment intersects an odd number of lines, the answer is different, when an even number of lines intersect, it is the same; so the difficulty lies in how to judge the intersection;
judge the intersection can be judged by a vector;
specific analysis As follows:
Insert picture description here
According to the right-hand rule, as long as the signs of the two cross products are opposite, it means that the CD line segment and the AB line intersect;
so the AC code:

#include<bits/stdc++.h>
using namespace std;
struct Point{
    
    
	int x,y;
	Point(int xx,int yy){
    
    
		  x=xx;y=yy;
	} 
	Point(){
    
    }
	int operator^(Point b){
    
    //重载的叉积
	     return x*b.y-b.x*y;  
	}
	Point operator-(Point b){
    
    
	     return Point(x-b.x,y-b.y);
	}
}p[20050],s,e;
bool intersect(Point A,Point B,Point C,Point D){
    
    
	Point AB=B-A;
	int t1=AB^(C-A);
	int t2=AB^(D-A);
	if((t1>0&&t2<0)||(t1<0&&t2>0)) return true;//判断是否相交
	else return false;
}
int main(){
    
    
	int S;
	scanf("%d",&S);
	int g=0;
	for(int i=0;i<S;i++){
    
    
		  scanf("%d %d %d %d",&p[g].x,&p[g].y,&p[g+1].x,&p[g+1].y);
		  g+=2;
	}
	int T;
	scanf("%d",&T);
	for(int i=0;i<T;i++){
    
    
		int num=0;
		   scanf("%d %d %d %d",&s.x,&s.y,&e.x,&e.y);
		   for(int j=0;j<g;j+=2){
    
    
		   	  if(intersect(p[j],p[j+1],s,e)){
    
    
		   	  	     num++;
				 }
		   }
		   if(num&1){
    
    
		   	  puts("different");
		   }else{
    
    
		   	  puts("same");
		   }
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/qq_44555205/article/details/104579631