POJ3335Rotating Scoreboard
题意:
给你一个多边形,问是否有一个区域能被所有边界上看到。
思路:
求多边形的核,自然用到半平面交。但是所给点的顺序不知道是顺时针还是逆时针序,我们可以通过求面积来判断,如果面积为正,那么就是逆时针序;反之为顺时针序。然后把直线方向全部按逆时针给出,这样的半平面交才正确。
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<ctype.h>
#include<queue>
#include<set>
#include<stack>
#include<cmath>
#include<map>
#define pii pair<int,int>
#define ll long long
#define cl(x,y) memset(x,y,sizeof(x))
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define lson x<<1,l,mid
#define rson x<<1|1,mid+1,r
#define INF 1e18
const int N=1e4+10;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const double eps=1e-8;
const double pi=acos(-1);
using namespace std;
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 xx,double yy){x=xx;y=yy;}
point operator +(point b){return point(x+b.x,y+b.y);}
point operator -(point b){return point(x-b.x,y-b.y);}
double operator ^(point b){return x*b.y-y*b.x;}//叉乘
double operator *(point b){return x*b.x+y*b.y;}//点乘
point operator *(double b){return point(x*b,y*b);}//数乘
double gettan(){return atan2(y,x);}//角度
void read(){scanf("%lf%lf",&x,&y);}
}p[N];
struct line
{
point s,e,l;
line(){}
line(point ss,point ee){s = ss;e = ee;l=e-s;}
void read(){s.read(),e.read();l=e-s;}
double gettan(){return atan2(e.y-s.y,e.x-s.x);}
};
point getcross(line l1,line l2)
{
double s1=((l2.s-l1.s)^(l2.e-l1.s));
double s2=((l2.e-l1.e)^(l2.s-l1.e));
if(s1+s2==0)//平行
return point{inf,inf};
return l1.s+l1.l*(s1/(s1+s2));
}
int cmp(line a,line b)
{
double t1=a.gettan(),t2=b.gettan();
if(sgn(t1-t2)==0)
return (a.l^(b.e-a.s))>0;
return t1<t2;
}
//判断bc交点是否在a的右边,如果在,去掉头部或者尾部的线
int onright(line a,line b,line c)
{
point p=getcross(b,c);
return sgn(a.l^(p-a.s))<0;
}
//半平面交
int hpi(line li[],int n)
{
line que[N];
sort(li+1,li+n+1,cmp);
int l=1,r=1,cnt=0,i;//模拟deque
//去重,极角相同取左边,即保留最后直线
for(i=1;i<n;i++)
if(sgn(li[i].gettan()-li[i+1].gettan()))
li[++cnt]=li[i];
li[++cnt]=li[n];
//判断新加入线的影响
for(i=1;i<=cnt;i++)
{
while(r-l>1 && onright(li[i],que[r-1],que[r-2]))
r--;
while(r-l>1 && onright(li[i],que[l],que[l+1]))
l++;
que[r++]=li[i];
}
//判断最先和最后加入的直线的影响
while(r-l>1 && onright(que[l],que[r-1],que[r-2]))
r--;
while(r-l>1 && onright(que[r-1],que[l],que[l+1]))
l++;
return r-l>=3;
}
double askarea(point d[],int n)
{
d[n+1]=d[1];
double area=0;
for(int i=1;i<=n;i++)
area+=(d[i]^d[i+1]);
area/=2;
return area;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
line l[N];
int i,len=0,n;
scanf("%d",&n);
for(i=1;i<=n;i++)
p[i].read();
if(askarea(p,n)>=0)
{
for(i=1;i<n;i++)
l[++len]=line(p[i],p[i+1]);
l[++len]=line(p[n],p[1]);
}
else
{
for(i=1;i<=n;i++)
l[++len]=line(p[i+1],p[i]);
l[++len]=line(p[1],p[n]);
}
cout<<(hpi(l,len)?"YES":"NO")<<endl;
}
return 0;
}