HDU 1828 / POJ 1177 Picture --线段树求矩形周长并

题意:给n个矩形,求矩形周长并

解法:跟求矩形面积并差不多,不过线段树节点记录的为:

len: 此区间线段长度

cover: 此区间是否被整个覆盖

lmark,rmark: 此区间左右端点是否被覆盖

num: 此区间分离开的线段的条数

重点在转移的地方,不难理解。

代码:

#include <iostream>
#include <cmath>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
#define N 10007 struct node
{
int cov,len,num,lmark,rmark;
}tree[*N]; struct Line
{
int y1,y2,x;
int cov;
}line[*N];
int yy[*N]; int cmp(Line ka,Line kb)
{
return ka.x < kb.x;
} int bsearch(int l,int r,int x)
{
while(l <= r)
{
int mid = (l+r)/;
if(x == yy[mid])
return mid;
if(x > yy[mid])
l = mid+;
else
r = mid-;
}
return l;
} void build(int l,int r,int rt)
{
tree[rt].cov = tree[rt].len = tree[rt].num = tree[rt].lmark = tree[rt].rmark = ;
if(l == r-) return;
int mid = (l+r)/;
build(l,mid,*rt);
build(mid,r,*rt+);
} void pushup(int l,int r,int rt)
{
if(tree[rt].cov)
{
tree[rt].len = yy[r]-yy[l];
tree[rt].lmark = tree[rt].rmark = ;
tree[rt].num = ;
}
else if(l+ == r)
tree[rt].len = tree[rt].num = tree[rt].lmark = tree[rt].rmark = ;
else
{
tree[rt].len = tree[*rt].len + tree[*rt+].len;
tree[rt].lmark = tree[*rt].lmark;
tree[rt].rmark = tree[*rt+].rmark;
tree[rt].num = tree[*rt].num+tree[*rt+].num-tree[*rt].rmark*tree[*rt+].lmark;
//如果左右区间连续,那么可以合并,减少一个区间
}
} void update(int l,int r,int aa,int bb,int cover,int rt)
{
if(aa <= l && bb >= r)
{
tree[rt].cov += cover;
pushup(l,r,rt);
return;
}
if(l+ == r) return;
int mid = (l+r)/;
if(aa <= mid)
update(l,mid,aa,bb,cover,*rt);
if(bb > mid)
update(mid,r,aa,bb,cover,*rt+);
pushup(l,r,rt);
} int main()
{
int n,m,cs = ,i,j;
int x1,y1,x2,y2;
while(scanf("%d",&n)!=EOF)
{
m = ;
for(i=;i<n;i++)
{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
line[m].x = x1,line[m].y1 = y1,line[m].y2 = y2,line[m].cov = ,yy[m++] = y1;
line[m].x = x2,line[m].y1 = y1,line[m].y2 = y2,line[m].cov = -,yy[m++] = y2;
}
m--;
sort(yy+,yy+m+);
int cnt = ;
for(i=;i<=m;i++)
{
if(yy[i] != yy[i-])
yy[cnt++] = yy[i];
}
cnt--;
build(,cnt,);
sort(line+,line+m+,cmp);
int ans = ;
int last = ;
for(i=;i<=m;i++)
{
int L = bsearch(,cnt,line[i].y1);
int R = bsearch(,cnt,line[i].y2);
update(,cnt,L,R,line[i].cov,);
ans += abs(last - tree[].len);
if(i == m) break;
ans += tree[].num**(line[i+].x-line[i].x);
last = tree[].len;
}
printf("%d\n",ans);
}
return ;
}
上一篇:Android布局_表格布局TableLayout


下一篇:第二篇、为UITableViewCell 高度自适应加速 缓存cell的高度