[poj2318]TOYS(直线与点的位置关系)

解题关键:计算几何入门题,通过叉积判断。

两个向量的关系:

P*Q>0,Q在P的逆时针方向;

P*Q<0,Q在P的顺时针方向;

P*Q==0,Q与P共线。

实际就是用右手定则判断的。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<iostream>
using namespace std;
typedef long long ll;
struct point{
    int x,y;  
};
int n,m,x1,x2,y11,y2; 
struct Line{
    point a,b;
}A[5010];
double operator*(point p1,point p2){return p1.x*p2.y-p2.x*p1.y;}
point operator-(point A,point B){return {A.x-B.x,A.y-B.y};}
int pos[5010];
bool judge(point t,int mid){//叉积 
    point tt=A[mid].b-A[mid].a; 
    int ans=tt*(t-A[mid].a);
    return ans<=0;
}

int erfen(point xx){  
    int l=0,r=n;  
    while(l<r){
        int mid=(l+r)>>1;  
        if(judge(xx,mid))  r=mid;
        else l=mid+1; 
    }
    return r;
}

int main(){ 
    while(scanf("%d",&n)!=EOF&&n){  
        scanf("%d%d%d%d%d",&m,&x1,&y11,&x2,&y2);  
        for(int i=0;i<n;i++){
            int xd,xu;
            scanf("%d%d",&xu,&xd);
            A[i]={{xu,y11},{xd,y2}};
        }
        memset(pos,0,sizeof pos);
        for(int i=0;i<m;i++){
            int xx,yy;
            scanf("%d%d",&xx,&yy);
            point t={xx,yy};
            int ans=erfen(t);
            pos[ans]++;
        }
        for(int i=0;i<=n;i++){  
            printf("%d: %d
",i,pos[i]); 
        }
        printf("
");
    }  
    return 0;  
}  
原文地址:https://www.cnblogs.com/elpsycongroo/p/8723586.html