ZOJ1010 Area (Asia 2001, Shanghai,计算几何)

题目大意是,给出一些点,这些点按顺序连接边,是否能围成一个多边形,能的话,输出多边形的面积,否则就输出不能。

相信多数 WA  的盆友都和我一样是错在多边形判断那个环节了,题目说的不是太清楚,经测试,以及网上的各路大神的指点,这题包括两条边重合,两点重合,一个点和除了与其相邻的两条边外的边重叠等这些不规则相交都要输出"Impossible",其他的应该就没什么问题了。

我的处理方案是,对于 p[i] 从 p[i+2] 开始,依次扫描 n-3 条边,看边 p[i] ,p[i+1] 是否和这些边相交,如果都不相交,就可以组成多边形。

 

#include<stdio.h>
#include<math.h>
#define N 1005
int blank,time,n;
#define eps 1e-5
bool dy(double x,double y)	{	return x > y + eps;}	// x > y 
bool xy(double x,double y)	{	return x < y - eps;}	// x < y 
bool dyd(double x,double y)	{ 	return x > y - eps;}	// x >= y 
bool xyd(double x,double y)	{	return x < y + eps;} 	// x <= y 
bool dd(double x,double y) 	{	return fabs( x - y ) < eps;}  // x == y

double max(double x,double y)
{
	if(dy(x,y))return x;
	return y;
}
double min(double x,double y)
{
	if(xy(x,y))return x;
	return y;
}

struct point 
{
	double x,y;
};

point p[N];

double dis(point a,point b)
{
	return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

int gongxian(point a,point b,point c)
{
	if(a.x==b.x && c.x==b.x)return 1;
	else if( dd( (b.y-a.y)/(b.x-a.x),(c.y-b.y)/(c.x-b.x) ) )return 1;
	return 0;
}

double fun_s(point a,point b,point c)
{
	double d1,d2,d3;
	d1=dis(a,b); d2=dis(a,c); d3=dis(b,c);
	double p=(d1+d2+d3)/2;
	return sqrt(p*(p-d1)*(p-d2)*(p-d3));
}

void solve1()
{
	if(!blank)blank=1;
	else puts("");
	printf("Figure %d: ",time++);
	if(n<3)printf("Impossible\n");
	else 
	{
		if(gongxian(p[0],p[1],p[2]))//三点共线
			printf("Impossible\n");
		else 
		{
			double s=fun_s(p[0],p[1],p[2]);
			printf("%.2lf\n",s);
		}
	}
}

double xmult(point a,point b,point c)
{
	return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
}

int onSegment(point a, point b, point c)
{
	if( dd(xmult(a,b,c),0.0) && dyd(c.x,min(a.x,b.x)) && 
	xyd(c.x,max(a.x,b.x)) && dyd(c.y,min(a.y,b.y)) && xyd(c.y,max(a.y,b.y)) )
		return 1;
	return 0;
}

int is_Cross(point a,point b,point c,point d)
{
	double d1=xmult(c,d,a);
	double d2=xmult(c,d,b);
	double d3=xmult(a,b,c);
	double d4=xmult(a,b,d);
	if(xy(d1*d2,0.0) && xy(d3*d4,0.0))return 1;
	if( dd(d1,0.0) && onSegment(c,d,a) || dd(d2,0.0) && onSegment(c,d,b)
	 || dd(d3,0.0) && onSegment(a,b,c) || dd(d4,0.0) && onSegment(a,b,d) )
	 	return 1;
	return 0;
}

int judge_1()//构不成多边形,返回1,可以的话返回0,判断每条边和除相邻两条边外的其他变相交
{
	p[n]=p[0];
	for(int i=0;i<n;i++)
	{
		for(int j=i+2;j<i+2+n-3;j++)
			if(is_Cross(p[i%n],p[(i+1)%n],p[j%n],p[(j+1)%n]))
				return 1;
	}
	return 0;
}

double area_polygon()
{
	double s = 0.0;
	for(int i=0; i<n; i++)
		s += p[(i+1)%n].y * p[i].x - p[(i+1)%n].x * p[i].y;
	return fabs(s)/2.0;
}

void solve2()
{
	if(!blank)blank=1;
	else puts("");
	printf("Figure %d: ",time++);
	if( judge_1() ) printf("Impossible\n");
	else
	{
		double s=area_polygon();
		printf("%.2lf\n",s);
	}
}

int main()
{
	int i;
	time=1;
	while(scanf("%d",&n),n)
	{
		for(i=0;i<n;i++)
			scanf("%lf%lf",&p[i].x,&p[i].y);
		if(n<4) solve1();
		else solve2();
	}
	return 0;
}


 

你可能感兴趣的:(c,struct,测试,ini,fun)