计算两个多边形的重叠面积(C++)
法一
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
const int maxn = 300;
const double eps = 1e-6;
int dcmp(double x)
{
if(x > eps) return 1;
return x < -eps ? -1 : 0;
}
struct Point
{
double x, y;
};
double cross(Point a, Point b, Point c)
{
return (a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
}
Point intersection(Point a, Point b, Point c, Point d)
{
Point p = a;
double t =((a.x-c.x)*(c.y-d.y)-(a.y-c.y)*(c.x-d.x))/((a.x-b.x)*(c.y-d.y)-(a.y-b.y)*(c.x-d.x));
p.x +=(b.x-a.x)*t;
p.y +=(b.y-a.y)*t;
cout << "intersection p.x=" << p.x << ", p.y=" << p.y << endl;
return p;
}
double PolygonArea(Point p[], int n)
{
if(n < 3) return 0.0;
double s = p[0].y * (p[n - 1].x - p[1].x);
for(int i = 1; i < n - 1; ++ i) {
s += p[i].y * (p[i - 1].x - p[i + 1].x);
}
s += p[n - 1].y * (p[n - 2].x - p[0].x);
cout << "s =" << s << endl;
return fabs(s * 0.5);
}
double CPIA(Point a[], Point b[], int na, int nb)
{
Point p[20], tmp[20];
int tn, sflag, eflag;
memcpy(p,b,sizeof(Point)*(nb));
for(int i = 0; i < na && nb > 2; i++)
{
if (i == na - 1) {
sflag = dcmp(cross(a[0], p[0],a[i]));
} else {
sflag = dcmp(cross(a[i + 1], p[0],a[i]));
}
for(int j = tn = 0; j < nb; j++, sflag = eflag)
{
if(sflag>=0) {
tmp[tn++] = p[j];
}
if (i == na - 1) {
if (j == nb -1) {
eflag = dcmp(cross(a[0], p[0], a[i]));
} else {
eflag = dcmp(cross(a[0], p[j + 1], a[i]));
}
} else {
if (j == nb -1) {
eflag = dcmp(cross(a[i + 1], p[0], a[i]));
} else {
eflag = dcmp(cross(a[i + 1], p[j + 1], a[i]));
}
}
if((sflag ^ eflag) == -2) {
if (i == na - 1) {
if (j == nb -1) {
tmp[tn++] = intersection(a[i], a[0], p[j], p[0]);
} else {
tmp[tn++] = intersection(a[i], a[0], p[j], p[j + 1]);
}
} else {
if (j == nb -1) {
tmp[tn++] = intersection(a[i], a[i + 1], p[j], p[0]);
} else {
tmp[tn++] = intersection(a[i], a[i + 1], p[j], p[j + 1]);
}
}
}
}
memcpy(p, tmp, sizeof(Point) * tn);
nb = tn, p[nb] = p[0];
}
if(nb < 3) return 0.0;
return PolygonArea(p, nb);
}
double SPIA(Point a[], Point b[], int na, int nb)