题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1264
题意:求矩形面积并
思路:做过好几次了,还算熟练……就是给出的点不一定是正对角线的点坑了好久
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 1000300
using namespace std;
struct Tree
{
int l,r,date,tsum;
} tree[maxn*3];
struct Node
{
int l,r,h,date;
} s[maxn];
int lazy[maxn*3],pos[maxn],cnt;
bool cmp(Node p,Node q)
{
return p.h<q.h;
}
void getlen(int root)
{
if (lazy[root]>0)
tree[root].tsum=pos[tree[root].r+1]-pos[tree[root].l];
else if (tree[root].l==tree[root].r)
tree[root].tsum=0;
else tree[root].tsum=tree[root<<1].tsum+tree[root<<1|1].tsum;
}
void build(int root,int l,int r)
{
tree[root].l=l;
tree[root].r=r;
tree[root].tsum=0;
if (l==r) return;
int mid=(l+r)>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
}
void update(int root,int l,int r,int val)
{
if (tree[root].l>=l && tree[root].r<=r)
{
lazy[root]+=val;
getlen(root);
return;
}
int mid=(tree[root].l+tree[root].r)>>1;
if (l<=mid) update(root<<1,l,r,val);
if (r>mid) update(root<<1|1,l,r,val);
getlen(root);
}
void getpoint(int x1,int x2,int y1,int date)
{
s[cnt].l=x1;
s[cnt].r=x2;
s[cnt].h=y1;
s[cnt].date=date;
cnt++;
}
int main()
{
int x1,x2,y1,y2,num,flag=1;
while (scanf("%d%d%d%d",&x1,&y1,&x2,&y2)!=EOF)
{
cnt=0;
num=0;
if( x1 > x2 ) //把坐标1作为左上角 2作为右下角
swap( x1,x2 );
if( y1 > y2 )
swap( y1,y2 );
getpoint(x1,x2,y1,1);
getpoint(x1,x2,y2,-1);
pos[num++]=x1;
pos[num++]=x2;
while (scanf("%d%d%d%d",&x1,&y1,&x2,&y2))
{
if (x2==-1 || x2==-2)
{
if (x2==-2) flag=0;
break;
}
if(x1>x2) swap(x1,x2);
if(y1>y2) swap(y1,y2);
getpoint(x1,x2,y1,1);
getpoint(x1,x2,y2,-1);
pos[num++]=x1;
pos[num++]=x2;
}
sort(s,s+cnt,cmp);
sort(pos,pos+num);
int tem=1;
for (int i=1; i<num; i++)
{
if (pos[i]!=pos[i-1])
pos[tem++]=pos[i];
}
build(1,0,tem);
memset(lazy,0,sizeof(lazy));
int res=0;
for (int i=0; i<cnt-1; i++)
{
int l=lower_bound(pos,pos+tem,s[i].l)-pos;
int r=lower_bound(pos,pos+tem,s[i].r)-pos-1;
update(1,l,r,s[i].date);
res+=tree[1].tsum*(s[i+1].h-s[i].h);
}
printf("%d\n",res);
if (!flag) break;
}
}