一點心得:
這一題是我學掃描線的第一題,掃描線的原理是比較好理解的,主要是離散化座標後用線段樹維護x或是y軸上的線段,乘以掃描線所經過的距離就是面積了。
這裏有一個我看到的解釋掃描線的博客:掃描線的解釋 >”<
我感覺的話掃描線主要難的地方,一定要選點靠譜的代碼~剛開始一直在看某個博主的奇技淫巧~T_T,一直沒看懂。後來換了代碼,就很容易懂了。這裏給出這位大神的Blog:HDU - 1542 >”<
emmm,然後就是我這個弱雞的代碼嘍~畢竟自己寫的代碼比較符合自己的風格,會舒服很多哦~
由於這題條件特殊,所以沒有去除重複部分的操作~
代碼:
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 1e3+9;
double y[MAX_N];
struct Line
{
double x,y1,y2; // y1 < y2
int flag;
}line[300];
struct Node
{
int l,r,cover;
double lf,rf,len;
}node[MAX_N];
bool cmp(const Line & A,const Line & B)
{
return A.x < B.x;
}
void build(int rt,int l,int r)
{
node[rt].l = l; node[rt].r = r;
node[rt].lf = y[l]; node[rt].rf = y[r];
node[rt].len = node[rt].cover = 0;
if(l+1 == r) return ;
int mid = (l+r) >> 1;
build(rt<<1,l,mid);
build(rt<<1|1,mid,r);
}
void push_up(int rt)
{
if(node[rt].cover > 0)
{
node[rt].len = node[rt].rf - node[rt].lf;
return;
}
else if(node[rt].l+1 == node[rt].r)
{
node[rt].len = 0;
}
else
{
node[rt].len = node[rt<<1].len + node[rt<<1|1].len;
}
}
void updata(int rt,Line t)
{
if(t.y1 == node[rt].lf && t.y2 == node[rt].rf)
{
node[rt].cover += t.flag;
push_up(rt);
return;
}
if(t.y1 >= node[rt<<1|1].lf)
{
updata(rt<<1|1 , t);
}
else if(t.y2 <= node[rt<<1].rf)
{
updata(rt<<1 , t);
}
else
{
Line temp = t;
temp.y2 = node[rt<<1].rf;
updata(rt<<1 , temp);
temp = t;
temp.y1 = node[rt<<1|1].lf;
updata(rt<<1|1 , temp);
}
push_up(rt);
}
int main()
{
int N,M,T=1;
while(cin>>N)
{
if(N==0) break;
int cnt = 0;
for(int i=0;i<N;i++)
{
double x1,y1,x2,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
line[cnt].x = x1;
line[cnt].y1 = y1;
line[cnt].y2 = y2;
line[cnt].flag = 1;
y[cnt++] = y1;
line[cnt].x = x2;
line[cnt].y1 = y1;
line[cnt].y2 = y2;
line[cnt].flag = -1;
y[cnt++] = y2;
}
sort(line,line+cnt,cmp);
sort(y,y+cnt);
build(1,0,cnt-1);
updata(1,line[0]);
double ans = 0;
for(int i=1;i<cnt;i++)
{
ans += node[1].len*(line[i].x - line[i-1].x);
updata(1,line[i]);
}
cout<<"Test case #"<<T<<endl;
printf("Total explored area: %.2lf\n\n",ans);
T++;
}
return 0;
}