http://poj.org/problem?id=1151
题意是 给你n个矩形的坐标 求矩形覆盖的总面积
离散化
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#define M 300
#define eps 1e-6
using namespace std;
struct trangle
{
double x1,y1,x2,y2;
}trg[105];
int n,xi,yi;
double xx[M],yy[M];
double ss[M][M];
double tot_s;
bool Had_add[M][M];
int findxi(double x)
{
int l=0,r=xi-1,mid,ans;
while(l<=r)
{
mid=(l+r)/2;//printf("%d %d %lf\n",l,r,xx[mid]);
if(fabs(xx[mid]-x)<eps) break;
else if(xx[mid]-x<0)
l=mid+1;
else
r=mid-1;
}//printf("---%d\n",mid);
return mid;
}
int findyi(double y)
{
int l=0,r=yi-1,mid,ans;
while(l<=r)
{
mid=(l+r)/2;//printf("%d %d %lf\n",l,r,xx[mid]);
if(fabs(yy[mid]-y)<eps) break;
else if(yy[mid]-y<-eps)
l=mid+1;
else if(yy[mid]-y>eps)
r=mid-1;
}//printf("---%d\n",mid);
return mid;
}
void solve()
{
int i,j,k;
int x,y;
double x1,x2,y1,y2;
sort(xx,xx+xi);
sort(yy,yy+yi);
//for(i=1;i<xi;i++)
//for(j=1;j<yi;j++)
//ss[i][j]=(xx[i]-xx[i-1])*(yy[j]-yy[j-1])*1.0;
memset(Had_add,false,sizeof(Had_add));
tot_s=0;
for(k=1;k<=n;k++)
{
x1=trg[k].x1; y1=trg[k].y1;
x2=trg[k].x2; y2=trg[k].y2;
x=findxi(x1);
y=findyi(y1);
//printf("--%d %d\n",x,y);
for(i=x+1;xx[i]-x2<=eps&&i<xi;i++)
{
for(j=y+1;yy[j]-y2<=eps&&j<yi;j++)
{
if(!Had_add[i][j])
{
//printf("%d %d\n",i,j);
//tot_s+=ss[i][j];
//printf("ss[%d][%d]=%f %f\n",i,j,ss[i][j],(xx[i]-xx[i-1])*(yy[j]-yy[j-1]));
tot_s=tot_s+(xx[i]-xx[i-1])*(yy[j]-yy[j-1]);
Had_add[i][j]=true;
}
}
}
}
}
int main()
{
double a,b,c,d,t;
int i,cas=1;
while(scanf("%d",&n)&&n)
{
xi=yi=0;
for(i=1;i<=n;i++)
{
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
if(a-c>eps)
{
t=a; a=c; c=t;
t=b; b=d; d=t;
}
trg[i].x1=a; trg[i].y1=b;
trg[i].x2=c; trg[i].y2=d;
xx[xi++]=a; xx[xi++]=c;
yy[yi++]=b; yy[yi++]=d;
}
solve();
printf("Test case #%d\nTotal explored area: %.2f\n\n",cas++,tot_s);
}
return 0;
}