【线段树+扫描线】 HDOJ 1542 Atlantis

线段树+扫描线+离散化,由于写过线段树+扫描线的题目,写着到题比较轻松~~~只要用once记录至少一次覆盖的面积,再用cover记录覆盖的次数就可以轻松解决了~~~

#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <climits>
#define maxn 205
#define eps 1e-6
#define mod 200000007
#define INF 99999999
#define lowbit(x) (x&(-x))
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
typedef long long LL;
using namespace std;


double once[maxn<<2];
int cover[maxn<<2];
double x[maxn];
struct node
{
double x1, x2, h;
int flag;
}line[maxn];
int cnt, xcnt;
int n, ql, qr, k;


int cmp1(double a, double b)
{
return a<b;
}
int cmp2(node a, node b)
{
return a.h<b.h;
}
int search(double tmp)
{
int bot=1, top=xcnt, mid;
while(top>=bot){
mid=(top+bot)>>1;
if(abs(x[mid]-tmp)<eps) break;
if(x[mid]>tmp) top=mid-1;
else bot=mid+1;
}
return mid;
}
void read(void)
{
int i, j;
for(i=0, j=0;i<n;i++){
scanf("%lf%lf%lf%lf", &line[j].x1, &line[j].h, &line[j+1].x2, &line[j+1].h);
line[j].x2=line[j+1].x2, line[j+1].x1=line[j].x1;
line[j].flag=1, line[j+1].flag=-1;
x[j+1]=line[j].x1, x[j+2]=line[j+1].x2, j+=2;
}
cnt=j;
}
void work(void)
{
sort(x+1, x+cnt+1, cmp1);
sort(line, line+cnt, cmp2);
int i, j;
for(i=2, j=2;i<=cnt;i++)
if(abs(x[i]-x[i-1])>eps)
x[j++]=x[i];
xcnt=j-1;
}
void init(void)
{
memset(once, 0, sizeof once);
memset(cover, 0, sizeof cover);
}
void pushup(int o, int L, int R)
{
if(cover[o]==0) once[o]=once[o<<1]+once[o<<1 | 1];
else once[o]=x[R+1]-x[L];
}
void updata(int o, int L, int R)
{
if(ql<=L && qr>=R){
cover[o]+=k;
pushup(o, L, R);
return;
}
int mid=(R+L)>>1;
if(ql<=mid) updata(lson);
if(qr>mid) updata(rson);
pushup(o, L, R);
}
double solve(void)
{
double res=0, tmp=0;
for(int i=0;i<cnt;i++){
res+=once[1]*(line[i].h-tmp);
tmp=line[i].h;
ql=search(line[i].x1);
qr=search(line[i].x2)-1;
k=line[i].flag;
updata(1, 1, xcnt-1);
}
return res;
}
int main(void)
{
int _=0;
while(scanf("%d",&n),n!=0){
init();
read();
work();
printf("Test case #%d\n", ++_);
printf("Total explored area: %.2f\n", solve());
printf("\n");
}
return 0;
}

你可能感兴趣的:(线段树,HDU,扫描线)