BZOJ1845 : [Cqoi2005] 三角形面积并

求出所有交点后从左往右扫描线,用每段的中位线去截所有三角形,算出长度并后乘以该段长度即可,时间复杂度$O(n^3\log n)$。

 

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=310;
const double eps=1e-9,inf=2000000;
struct P{
  double x,y;
  P(){x=y=0;}
  P(double _x,double _y){x=_x,y=_y;}
  P operator+(P v){return P(x+v.x,y+v.y);}
  P operator-(P v){return P(x-v.x,y-v.y);}
  P operator*(double v){return P(x*v,y*v);}
  P operator/(double v){return P(x/v,y/v);}
  double operator*(P v){return x*v.x+y*v.y;}
}tri[N][4],seg[N];
inline bool cmp(P a,P b){return a.x<b.x;}
double px[N*N],ans;
int n,i,j,k,l,m;
inline int sig(double x){
  if(fabs(x)<eps)return 0;
  return x>0?1:-1;
}
inline double cross(P a,P b){return a.x*b.y-a.y*b.x;}
inline bool has_intersection(P a,P b,P p,P q){
  int d1=sig(cross(b-a,p-a)),d2=sig(cross(b-a,q-a)),
      d3=sig(cross(q-p,a-p)),d4=sig(cross(q-p,b-p));
  return d1*d2<0&&d3*d4<0;
}
inline P line_intersection(P a,P b,P p,P q){
  double U=cross(p-a,q-p),D=cross(b-a,q-p);
  return a+(b-a)*(U/D);
}
inline double cal(double x){
  P D(x,-inf),U(x,inf);
  int i,m=0;
  for(i=0;i<n;i++){
    int j=0,k=0;double y[2];
    for(j=0;j<3;j++)if(has_intersection(tri[i][j],tri[i][j+1],D,U))
      y[k++]=line_intersection(tri[i][j],tri[i][j+1],D,U).y;
    if(k)seg[m++]=P(min(y[0],y[1]),max(y[0],y[1]));
  }
  if(m>1)sort(seg,seg+m,cmp);
  double l=-inf,r=-inf,t=0;
  for(i=0;i<m;i++){
    if(sig(seg[i].x-r)>0)t+=r-l,l=seg[i].x;
    r=max(r,seg[i].y);
  }
  return t+r-l;
}
int main(){
  scanf("%d",&n);
  for(i=0;i<n;i++){
    for(j=0;j<3;j++)scanf("%lf%lf",&tri[i][j].x,&tri[i][j].y);
    tri[i][3]=tri[i][0];
  }
  for(i=0;i<n;i++)for(j=0;j<3;j++)px[m++]=tri[i][j].x;
  for(i=0;i<n;i++)for(j=0;j<i;j++)for(k=0;k<3;k++)for(l=0;l<3;l++)
    if(has_intersection(tri[i][k],tri[i][k+1],tri[j][l],tri[j][l+1]))
      px[m++]=line_intersection(tri[i][k],tri[i][k+1],tri[j][l],tri[j][l+1]).x;
  sort(px,px+m);
  for(i=1;i<m;i++)if(sig(px[i]-px[i-1]))ans+=(px[i]-px[i-1])*cal((px[i]+px[i-1])/2);
  return printf("%.2f",ans-eps),0;
}

  

posted @ 2015-12-21 01:32  Claris  阅读(684)  评论(2编辑  收藏  举报