模板题
题意:给定两个凸多边形,求出合并后的面积,这个合并后的面积不包括重叠部分。
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 #include<math.h> 5 #include<algorithm> 6 using namespace std; 7 const int maxn = 155; 8 const int maxm = 155; 9 const double eps = 1e-8; 10 const double pi = acos(-1.0); 11 struct Point{ 12 double x,y; 13 }; 14 struct Line{ 15 Point a,b; 16 }; 17 Point pnt1[ maxn ],res[ maxm ],pnt2[ maxn ],tp[ maxm ]; 18 double xmult( Point op,Point sp,Point ep ){ 19 return (sp.x-op.x)*(ep.y-op.y)-(sp.y-op.y)*(ep.x-op.x); 20 } 21 double dist( Point a,Point b ){ 22 return sqrt( (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y) ); 23 } 24 void Get_equation( Point p1,Point p2,double &a,double &b,double &c ){ 25 a = p2.y-p1.y; 26 b = p1.x-p2.x; 27 c = p2.x*p1.y-p1.x*p2.y; 28 }//直线方程 29 Point Intersection( Point p1,Point p2,double a,double b,double c ){ 30 double u = fabs( a*p1.x+b*p1.y+c ); 31 double v = fabs( a*p2.x+b*p2.y+c ); 32 Point tt; 33 tt.x = (p1.x*v+p2.x*u)/(u+v); 34 tt.y = (p1.y*v+p2.y*u)/(u+v); 35 return tt; 36 }//交点、按照三角比例求出交点 37 double GetArea( Point p[],int n ){ 38 double sum = 0; 39 for( int i=2;i<n;i++ ){ 40 sum += xmult( p[1],p[i],p[i+1] ); 41 } 42 return -sum/2.0; 43 }//面积,顺时针为正 44 void cut( double a,double b,double c,int &cnt ){ 45 int temp = 0; 46 for( int i=1;i<=cnt;i++ ){ 47 if( a*res[i].x+b*res[i].y+c>-eps ){//>=0 48 tp[ ++temp ] = res[i]; 49 } 50 else{ 51 if( a*res[i-1].x+b*res[i-1].y+c>eps ){ 52 tp[ ++temp ] = Intersection( res[i-1],res[i],a,b,c ); 53 } 54 if( a*res[i+1].x+b*res[i+1].y+c>eps ){ 55 tp[ ++temp ] = Intersection( res[i],res[i+1],a,b,c ); 56 } 57 } 58 } 59 for( int i=1;i<=temp;i++ ) 60 res[i] = tp[i]; 61 res[ 0 ] = res[ temp ]; 62 res[ temp+1 ] = res[ 1 ]; 63 cnt = temp; 64 } 65 66 int main(){ 67 int m,n; 68 while( scanf("%d",&n)==1,n ){ 69 for( int i=1;i<=n;i++ ){ 70 scanf("%lf%lf",&pnt1[i].x,&pnt1[i].y); 71 } 72 scanf("%d",&m); 73 for( int i=1;i<=m;i++ ){ 74 scanf("%lf%lf",&pnt2[i].x,&pnt2[i].y); 75 } 76 double sumArea1,sumArea2,Area; 77 sumArea1 = GetArea( pnt1,n ); 78 sumArea2 = GetArea( pnt2,m ); 79 if( sumArea1<eps ){ 80 reverse( pnt1+1,pnt1+1+n ); 81 } 82 pnt1[ 0 ] = pnt1[ n ]; 83 pnt1[ n+1 ] = pnt1[ 1 ]; 84 if( sumArea2<eps ){ 85 reverse( pnt2+1,pnt2+1+m ); 86 } 87 pnt2[ 0 ] = pnt2[ m ]; 88 pnt2[ m+1 ] = pnt2[ 1 ]; 89 for( int i=0;i<=n+1;i++ ){ 90 res[i] = pnt1[i]; 91 } 92 int cnt = n; 93 for( int i=1;i<=m;i++ ){ 94 double a,b,c; 95 Get_equation( pnt2[i],pnt2[i+1],a,b,c ); 96 cut(a,b,c,cnt); 97 } 98 Area = GetArea( res,cnt ); 99 double ans = fabs(sumArea1)+fabs(sumArea2)-2.0*fabs(Area); 100 printf("%8.2lf",ans); 101 } 102 puts(""); 103 return 0; 104 }