题解 计算几何 POJ 2318
题意:给一个矩形,用N个隔板分割矩形,放入M个物品,求每个方块内物品数。
做法:计算几何基础。先贴上point和line的模板(我是菜鸟),然后计算物品放置点和左下角组成的线段和隔板是否相 交,若没有相交,则该点在隔板左侧的空间内。
代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int num[5050];
const double eps = 1e-8;
const double PI = acos(-1.0);
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;
}
//绕原点旋转角度B(弧度值),后x,y的变化
void transXY(double B)
{
double tx = x,ty = y;
x = tx*cos(B) - ty*sin(B);
y = tx*sin(B) + ty*cos(B);
}
};
struct Line
{
Point s,e;
Line(){}
Line(Point _s,Point _e)
{
s = _s;e = _e;
}
//两直线相交求交点
//第一个值为0表示直线重合,为1表示平行,为0表示相交,为2是相交
//只有第一个值为2时,交点才有意义
pair<int,Point> operator &(const Line &b)const
{
Point res = s;
if(sgn((s-e)^(b.s-b.e)) == 0)
{
if(sgn((s-b.e)^(b.s-b.e)) == 0)
return make_pair(0,res);//重合
else return make_pair(1,res);//平行
}
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 make_pair(2,res);
}
};
bool inter(Line l1,Line l2)
{
return
max(l1.s.x,l1.e.x) >= min(l2.s.x,l2.e.x) &&
max(l2.s.x,l2.e.x) >= min(l1.s.x,l1.e.x) &&
max(l1.s.y,l1.e.y) >= min(l2.s.y,l2.e.y) &&
max(l2.s.y,l2.e.y) >= min(l1.s.y,l1.e.y) &&
sgn((l2.s-l1.e)^(l1.s-l1.e))*sgn((l2.e-l1.e)^(l1.s-l1.e)) <= 0 &&
sgn((l1.s-l2.e)^(l2.s-l2.e))*sgn((l1.e-l2.e)^(l2.s-l2.e)) <= 0;
}
int main()
{
int n,m;
double x1,y1,x2,y2;
Line card[5050];
while(1)
{
scanf("%d",&n);
if(n==0)
break;
memset(num,0,sizeof(num));
scanf("%d%lf%lf%lf%lf",&m,&x1,&y1,&x2,&y2);
int i,j;
double x,y,x3,x4;
Line line;
for(i=0;i<n;i++)
{
scanf("%lf%lf",&x3,&x4);
card[i].s.x=x3,card[i].s.y=y1;
card[i].e.x=x4,card[i].e.y=y2;
}
card[n].s.x=x2,card[n].s.y=y1,card[n].e.x=x2,card[n].e.y=y2;
for(i=0;i<m;i++)
{
scanf("%lf%lf",&x,&y);
line.s.x=x1,line.s.y=y2;
line.e.x=x,line.e.y=y;
int flag=0;
for(j=0;j<=n;j++)
if(card[j].s.x<x&&card[j].e.x<x)
flag=j;
for(j=flag;j<=n;j++)
{
if(inter(line,card[j])==0)
{num[j]++;break;}
}
}
for(i=0;i<=n;i++)
printf("%d: %d\n",i,num[i]);
printf("\n");
}
return 0;
}
错误:TLE:未增加限制条件,导致多次进行相交判定。
浙公网安备 33010602011771号