And two arbitrary polygon intersection area

#include<bits/stdc++.h>
using namespace std;
#define maxn 510
const double eps=1E-8;
int sig(double d){
return(d>eps)-(d<-eps);
}
struct Point{
double x,y; Point(){}
Point(double x,double y):x(x),y(y){}
bool operator==(const Point&p)const{
return sig(x-p.x)==0&&sig(y-p.y)==0;
}
};
double cross(Point o,Point a,Point b){
return(a.x-o.x)*(b.y-o.y)-(b.x-o.x)*(a.y-o.y);
}
double area(Point* ps,int n){
ps[n]=ps[0];
double res=0;
for(int i=0;i<n;i++){
res+=ps[i].x*ps[i+1].y-ps[i].y*ps[i+1].x;
}
return res/2.0;
}
int lineCross(Point a,Point b,Point c,Point d,Point&p){
double s1,s2;
s1=cross(a,b,c);
s2=cross(a,b,d);
if(sig(s1)==0&&sig(s2)==0) return 2;
if(sig(s2-s1)==0) return 0;
p.x=(c.x*s2-d.x*s1)/(s2-s1);
p.y=(c.y*s2-d.y*s1)/(s2-s1);
return 1;
}

// polygonal cutting
// p cutting a straight line ab & polygon, left after cutting in the vector (a, b) and in situ cleavage results save
// if reduced to a point, will go back, where n is . 1
void polygon_cut (Point * P, int & n-, Point A, Point B) {
static Point PP [MAXN];
int m = 0; P [n-] = P [0];
for (int I = 0; I <n-; I ++) {
IF (SIG (Cross (A, B, P [I]))> 0) PP [m ++] = P [I];
! IF (SIG (Cross (A, B, P [I])) = SIG (Cross (A, B, P [I +. 1])))
lineCross (A, B, P [I], P [I +. 1], PP [m ++]);
}
n-= 0;
for (int I = 0; I <m; I ++)
IF) (I || (PP [I] == PP [I-. 1]!!)
P [n-++] = PP [I];
the while (n->. 1 && P [n--. 1 ] == P [0]) N--;
}

// returns oab triangle and the triangle are cross ocd area, o is the origin //
Double intersectArea (Point A, Point B, Point C, Point D) {
Point O (0,0);
int S1 = SIG (Cross ( O, A, B));
int S2 = SIG (Cross (O, C, D));
IF (== 0 || S1 S2 == 0) return 0.0; // degraded area 0
IF (S1 = -1 =) the swap (A, B);
IF (S2 == -. 1) the swap (C, D);
Point P [10] = {O, A, B};
int n-=. 3;
polygon_cut (P, n- , O, C);
polygon_cut (P, n-, C, D);
polygon_cut (P, n-, D, O);
Double FABS RES = (Area (P, n-));
IF (S1 * S2 == -. 1 ) RES = -res; RES return;
}

// find two polygonal cross area
Double intersectArea (PS1 Point *, int N1, PS2 Point *, int N2) {
IF (Area (PS1, N1) <0) Reverse (PS1, PS1 + N1);
IF (Area ( PS2, N2) <0) Reverse (PS2, PS2 + N2);
PS1 [N1] = PS1 [0];
PS2 [N2] = PS2 [0];
Double RES = 0;
for (int I = 0; I < N1; I ++) {
for (int J = 0; J <N2; J ++) {
RES + = intersectArea (PS1 [I], PS1 [I +. 1], PS2 [J], PS2 [J +. 1]);
}
}
RES return;
}

// find two arbitrary simple polygons and area
Point PS1 [MAXN], PS2 [MAXN];
int N1, N2;
int main ()
{
! The while (Scanf ( "% D% D", & N1, & N2) = the EOF ) {
for (int I = 0; I <N1; I ++)
Scanf ( "% LF% LF", & PS1 [I] .x, & PS1 [I] .y);
for (int I = 0; I <N2; I ++)
Scanf ( "% LF% LF", & PS2 [I] .x, & PS2 [I] .y);
Double ANS = intersectArea (PS1, N1, PS2, N2);
ANS = FABS (Area (PS1, N1) ) + fabs (area (ps2, n2)) - ans; // repellent receiving
the printf ( "%. 2F \ n-.", ANS);
}
return 0;
}

Guess you like

Origin www.cnblogs.com/qq-1585047819/p/11921540.html