题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3685
思路:先求出多边形重心,放置的边一定为凸包边。判断重心是否落在边之间(求点到直线与点到线段的距离,判断)。
4
0 0
4 0
8 4
4 4
注意这种情况,重心不能在凸包边端点的垂线上。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const double eps=1e-10;
const int maxn=5e4+50;
struct Point
{
double x,y;
Point(double x=0,double y=0):x(x),y(y) {}
};
Point operator - (const Point &A,const Point &B)
{
return Point(A.x-B.x,A.y-B.y);
}
bool operator < (const Point &a,const Point &b)
{
return a.x<b.x||(a.x==b.x&&a.y<b.y);
}
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
return (x<0?-1:1);
}
bool operator == (const Point &a,const Point &b)
{
return dcmp(a.x-b.x)==0&&dcmp(a.y-b.y)==0;
}
double Dot(const Point &A,const Point &B)
{
return A.x*B.x+A.y*B.y;
}
double Cross(Point A, Point B)
{
return A.x*B.y-A.y*B.x;
}
double Length(const Point &A)
{
return sqrt(Dot(A,A));
}
double Area(Point A,Point B,Point C)
{
return Cross(B-A, C-A)/2.0;
}
Point centre_of_gravity(Point *p, int n)
{
Point G;
double s,sumS=0;
G.x=0,G.y=0;
for(int i=1; i<n-1; i++)
{
s=Area(p[0], p[i], p[i+1]);
sumS+=s;
G.x+=(p[0].x+p[i].x+p[i+1].x)*s;
G.y+=(p[0].y+p[i].y+p[i+1].y)*s;
}
G.x=G.x/sumS/3.0;
G.y=G.y/sumS/3.0;
return G;
}
int convex_hull(Point *p,Point *ch,int n)
{
sort(p,p+n);
int m=0;
for(int i=0; i<n; i++)
{
while(m>1&&Cross(ch[m-1]-ch[m-2],p[i]-ch[m-1])<=0)
m--;
ch[m++]=p[i];
}
int k=m;
for(int i=n-2; i>=0; i--)
{
while(m>k&&Cross(ch[m-1]-ch[m-2],p[i]-ch[m-1])<=0)
m--;
ch[m++]=p[i];
}
if(n>1) m--;
return m;
}
double DistanceToLine(const Point &P,const Point &A,const Point &B)
{
Point v1=B-A,v2=P-A;
return fabs(Cross(v1,v2))/Length(v1);
}
double DistanceToSegment(const Point &P,const Point &A,const Point &B)
{
if(A==B) return Length(P-A);
Point v1=B-A,v2=P-A,v3=P-B;
if(dcmp(Dot(v1,v2)<0)) return Length(v2);
else if(dcmp(Dot(v1,v3))>0) return Length(v3);
else return fabs(Cross(v1,v2))/Length(v1);
}
int n;
Point P[maxn],hull[maxn];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0; i<n; i++)
{
double x,y;
scanf("%lf%lf",&x,&y);
P[i]=Point(x,y);
}
int ans=0;
Point G=centre_of_gravity(P,n);
// cout<<G.x<<" "<<G.y<<endl;
int num=convex_hull(P,hull,n);
//cout<<num<<endl;
/*for(int i=0;i<num;i++)
cout<<hull[i].x<<" "<<hull[i].y<<endl;*/
for(int i=0; i<num; i++)
{
int j=(i+1)%num;
if (dcmp (Dot (G-hull[i], hull[j]-hull[i])) == 0 || dcmp (Dot (G-hull[j], hull[i]-hull[j])) == 0) continue;
double DS=DistanceToSegment(G,hull[i],hull[j]);
double DL=DistanceToLine(G,hull[i],hull[j]);
//cout<<DS<<" "<<DL<<endl;
if(dcmp(DS-DL)==0) ans++;
}
printf("%d\n",ans);
}
return 0;
}