题目链接:http://acm.cs.ecnu.edu.cn/problem.php?problemid=1624
求两个凸多边形的交的面积。
求两个凸多边形的交的面积。
代码如下:
//============================================================================
// Name : ecnu1624.cpp
// Author : LML_yigo
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include<cstdio>
#include<math.h>
#define eps 1e-8
#define inf 1e10
using namespace std;
const int maxn=100000;
struct point{double x,y;}p[maxn],q[maxn],save[maxn],temp[maxn];
int n,m,ns;
double xmult(point p1,point p2,point p0)
{
return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}
point intersection(point p1,point p2,point p3,point p4)
{
point ret=p1;
double t=((p1.x-p3.x)*(p3.y-p4.y)-(p1.y-p3.y)*(p3.x-p4.x))
/((p1.x-p2.x)*(p3.y-p4.y)-(p3.x-p4.x)*(p1.y-p2.y));
ret.x+=(p2.x-p1.x)*t;
ret.y+=(p2.y-p1.y)*t;
return ret;
}
void mycopy(point *s,point *t,int n)
{
int i;
for(i=0;i<n;i++)s[i]=t[i];
}
bool zero(double x){return x>0? x<eps : x >-eps;}
void getline(point p1,point p2,double &a,double &b,double &c)
{
a=p2.y-p1.y;
b=p1.x-p2.x;
c=p2.x*p1.y-p1.x*p2.y;
}
void pri(point *p,int n)
{
int i;
printf("ns: %d\n",n);
for(i=0;i<n;i++)printf("save:: %lf %lf\n",p[i].x,p[i].y);
}
void cut()
{
int i,j;
mycopy(temp,q,m);
ns=m;
p[n]=p[0];
for(i=0;i<n;i++)
{
int cnt=0;
temp[ns]=temp[0];
double a,b,c;
getline(p[i],p[i+1],a,b,c);
for(j=0;j<ns;j++)
{
if(a*temp[j].x+b*temp[j].y+c>=0)
{
save[cnt++]=temp[j];
}
else
{
if(a*temp[(j-1+ns)%ns].x+b*temp[(j-1+ns)%ns].y+c>0)
save[cnt++]=intersection(temp[j],temp[(j-1+ns)%ns],p[i+1],p[i]);
if(a*temp[j+1].x+b*temp[j+1].y+c>0)
save[cnt++]=intersection(temp[j],temp[j+1],p[i+1],p[i]);
}
}
ns=cnt;
mycopy(temp,save,cnt);
}
}
double area(point *p,int n)
{
int i;
double res=0;
for(i=0;i<n;i++)
{
res+=p[(i+1)%n].x*p[i].y-p[i].x*p[(i+1)%n].y;
}
return fabs(res/2);
}
int main() {
while(scanf("%d",&n)!=EOF)
{
int i;
for(i=0;i<n;i++)scanf("%lf%lf",&p[i].x,&p[i].y);
scanf("%d",&m);
for(i=0;i<m;i++)scanf("%lf%lf",&q[i].x,&q[i].y);
cut();
printf("%.2lf\n",area(save,ns));
}
return 0;
}