ECNU 1624 求交集多边形面积

分析:题意就是要求两个多边形相交的部分的面积如果会求多边形的核,这题就不难了,可以看我写的一篇POJ 1279 求多边形的核,因为本题已经说了给定的是顺时针方向,所以把POJ 1279的逆时针改下,再稍微改几个地方几可以了。

# include <stdio.h>
# include <math.h>
# define EPS 1e-8
  struct point
  {
      double x,y;
  };
  void Swap(point &a,point &b)
  {
      point t;
      t=a; a=b; b=t;
  }
  double Cross(point a,point b,point c)
  {
      return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
  }
  double Area(point v[1505],int n)
  {
      int i;
      double ans=0;
      for(i=1;i<n;i++)
        ans+=Cross(v[1],v[i],v[i+1]);
      if(fabs(ans/2)<EPS) return 0;
      return -ans/2;
  }
  void Equation(point p1,point p2,double &a,double &b,double &c)
  {
      a=p2.y-p1.y;
      b=p1.x-p2.x;
      c=p1.y*p2.x-p1.x*p2.y;
  }
  point Intersection(point p1,point p2,double a,double b,double c)
  {
      double s1,s2;
      point t;
      s1=fabs(a*p1.x+b*p1.y+c);
      s2=fabs(a*p2.x+b*p2.y+c);
      t.x=(p1.x*s2+p2.x*s1)/(s1+s2);
      t.y=(p1.y*s2+p2.y*s1)/(s1+s2);
      return t;
  }
  void Cut(double a,double b,double c,point q[1505],int &m)
  {
      int i,t=0;
      point v[1505];
      for(i=1;i<=m;i++)
      {
          if(a*q[i].x+b*q[i].y+c>-EPS)
            v[++t]=q[i];
          else
          {
              if(a*q[i-1].x+b*q[i-1].y+c>EPS)
                v[++t]=Intersection(q[i-1],q[i],a,b,c);
              if(a*q[i+1].x+b*q[i+1].y+c>EPS)
                v[++t]=Intersection(q[i],q[i+1],a,b,c);
          }
      }
      for(i=1;i<=t;i++)
        q[i]=v[i];
      q[0]=q[t]; q[t+1]=q[1]; m=t;
  }
  int main()
  {
      int i,n,m;
      double a,b,c;
      point p[1005],q[1005];
      scanf("%d",&n);
      for(i=1;i<=n;i++)
        scanf("%lf%lf",&p[i].x,&p[i].y);
      scanf("%d",&m);
      for(i=1;i<=m;i++)
        scanf("%lf%lf",&q[i].x,&q[i].y);
      p[n+1]=p[1]; q[0]=q[n]; q[n+1]=q[1];
      for(i=1;i<=n;i++)
      {
          Equation(p[i],p[i+1],a,b,c);
          Cut(a,b,c,q,m);
      }
      printf("%.2f\n",Area(q,m));
      return 0;
  }



你可能感兴趣的:(ACM)