题意:
计算一堆长方形面积
思路:
线段树扫描线模板
以前手动去重,现在用STL写了一次,感觉好看多了
错误及反思:
PE和多组
代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N = 201;
double segtree[N<<2];
int lazy[N<<2],n,T=0;
struct L{double x1,x2,y;int ta;
} line[201];
vector<double> id;
bool cmp(L w,L e)
{return w.y<e.y;
}
int get_id(double x)
{return lower_bound(id.begin(),id.end(),x)-id.begin();
}
void pushup(int l,int r,int rt)
{if(lazy[rt]) segtree[rt]=id[r+1]-id[l];else if(l==r) segtree[rt]=0;else segtree[rt]=segtree[rt<<1]+segtree[rt<<1|1];
}
void update(int L,int R,int v,int l,int r,int rt)
{if(L<=l&&R>=r){lazy[rt]+=v;pushup(l,r,rt);return ;}int m=(l+r)/2;if(L<=m) update(L,R,v,lson);if(R>m) update(L,R,v,rson);pushup(l,r,rt);return ;
}
int main()
{while(scanf("%d",&n)&&n){printf("Test case #%d\n",++T);for(int i=0;i<n;i++){scanf("%lf%lf%lf%lf",&line[i*2].x1,&line[i*2].y,&line[i*2+1].x2,&line[i*2+1].y);line[i*2].x2=line[i*2+1].x2;line[i*2+1].x1=line[i*2].x1;line[i*2].ta=1;line[i*2+1].ta=-1;id.push_back(line[i*2].x1);id.push_back(line[i*2].x2);}sort(id.begin(),id.end()),id.erase(unique(id.begin(),id.end()),id.end());sort(line,line+n*2,cmp);double ans=0;for(int i=0;i<n*2;i++){int l=get_id(line[i].x1);int r=get_id(line[i].x2);if(i) ans+=1.0*(line[i].y-line[i-1].y)*segtree[1];if(l<=r-1) update(l,r-1,line[i].ta,0,id.size()-2,1);}printf("Total explored area: %.2f\n",ans);id.clear();memset(segtree,0,sizeof(segtree));memset(lazy,0,sizeof(lazy));puts("");}
}