POJ 2318 TOYS

来源:互联网 发布:上古网络用语 编辑:程序博客网 时间:2024/06/05 07:38

POJ 2318 TOYS

计算几何 叉积 二分

传送门:POJ


题意

建议读原题。一个箱子,里面被隔成多个区域。给你一堆坐标,判断每个区域有几个点。


思路

因为区域的隔板是按从左到右的顺序给出的,所以二分搜索。判断时用叉积判断当前点在搜索隔板的左还是右。


代码

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <math.h>#include <stdlib.h>#include <time.h>using namespace std;const double eps=1e-8;const double PI=acos(-1.0);const int MAXN=5007;int sgn(double x)//符号函数{    if(fabs(x) < eps) return 0;    if(x < 0) return -1;    else return 1;}//点,向量struct Point{    double x,y;    Point(){}    Point(double _x,double _y)//构造    {        x=_x; y=_y;    }    Point operator -(const Point &b)const    {        return Point(x-b.x,y-b.y);    }    double operator ^(const Point &b)const//叉积    {        return x*b.y-y*b.x;    }    double operator *(const Point &b)const//点积    {        return x*b.x+y*b.y;    }};//线struct Line{    Point s,e;//两点    //double k;//斜率    Line(){}    Line(Point _s,Point _e)//构造    {        s=_s; e=_e;        //k=atan2(e.y-s.y,e.x-s.x);    }    Point operator &(const Line &b)const//求两直线交点    {        Point res=s;        double t=((s-b.s)^(b.s-b.e))/((s-e)^(b.s-b.e));        res.x+=(e.x-s.x)*t;        res.y+=(e.y-s.y)*t;        return res;    }};double dist(Point a,Point b)//两点间距离{    return sqrt((a-b)*(a-b));}Line line[MAXN];int res[MAXN];void BS(Point p,int n)//二分搜索{    int l=0,r=n-1;    while(l<r)    {        int mid=(l+r)/2;        if(((p-line[mid].s)^(line[mid].e-line[mid].s))>0)        {            r=mid;        }        else        {            l=mid+1;        }    }    if(((p-line[l].s)^(line[l].e-line[l].s))>0)    {        res[l]++;    }    else    {        res[l+1]++;    }}int main(){    int m,n,x1,x2,y1,y2;    while(scanf("%d%d%d%d%d%d",&n,&m,&x1,&y1,&x2,&y2)==6&&n!=0)    {        memset(line,0,sizeof(0));        memset(res,0,sizeof(res));        for(int i=0;i<n;i++)        {            int a,b;            scanf("%d%d",&a,&b);            line[i]=Line(Point(a,y1),Point(b,y2));        }        for(int j=0;j<m;j++)        {            int a,b;            scanf("%d%d",&a,&b);            Point tp=Point(a,b);            BS(tp,n);        }        for(int i=0;i<=n;i++)        {            printf("%d: %d\n",i,res[i]);        }        printf("\n");    }    return 0;}
0 0
原创粉丝点击