[Baltic 2001]Mars Maps

In the year 2051, several Mars expeditions have explored different areas of the red planet and produced maps
of these areas. Now, the BaSA (Baltic Space Agency) has an ambitious plan: they would like to produce a map
of the whole planet. In order to calculate the necessary effort, they need to know the total size of the area
for which maps already exist. It is your task to write a program that calculates this area.
Task
Write a program that:

* reads the description of map shapes from the input file mar.in,
* computes the total area covered by the maps,
* writes the result to the output file mar.out.
Input
The input file mar.in starts with a line containing a single integer N (1<=N<=10 000)
the number of available maps. Each of the following N lines describes a map. Each of these lines contains
four integers x1, y1, x2 and y2 (0<=x1the coordinates of, respectively, the bottom-left and the top-right corner of the mapped area.
Each map has rectangular shape, and its sides are parallel to the x- and y-axis of the coordinate system.
Output
The output should contain one integer A, the total explored area
(i.e. the area of the union of all rectangles).
Sample Input
2
10 10 20 20
15 15 25 30
Sample Output
225

#include<cstdio>
#include<algorithm>
using namespace std;
const int N=3e4;
int lazy[N*8+100],tree[N*8+100];
int read()
{
    int x=0,f=1;char ch=getchar();
    for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
    for (;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
    return x*f;
}
struct TREE
{
    int val,first,last,cnt;
}h[N+100];
bool cmp(TREE x,TREE y)
{
    if (x.val!=y.val) 
	    return x.val<y.val;
    return x.cnt>y.cnt;
}
 
void update(int p,int l,int r)
{
    if (lazy[p]) 
	    tree[p]=r-l;
    else 
	     if (l+1==r) 
		     tree[p]=0;
         else 
		     tree[p]=tree[p*2]+tree[p*2+1];
}
void change(int p,int l,int r,int x,int y,int k)
{
    if (x<=l&&r<=y)
    {
        lazy[p]+=k;
        update(p,l,r);
        return;
    }
    int mid=(l+r)>>1;
    if (x<mid) 
	     change(p*2,l,mid,x,y,k);
    if (y>mid) 
	     change(p*2+1,mid,r,x,y,k);
    update(p,l,r);
}
int main()
{
    int n=read();
    for (int i=1;i<=n;i++)
    {
        int x1=read(),y1=read(),x2=read(),y2=read();
        h[i].cnt=1; 
		h[n+i].cnt=-1;
        h[i].val=x1; h[i].first=y1; h[i].last=y2;
        h[n+i].val=x2; h[n+i].first=y1;h[n+i].last=y2;
    }
    sort(h+1,h+n*2+1,cmp);
    int ans=0;
    for (int i=1;i<=n*2;i++)
    {
        if (i!=1) //如果不是第一条竖线 
		     ans+=(h[i].val-h[i-1].val)*tree[1]; //算出矩形面积 
        change(1,0,N,h[i].first,h[i].last,h[i].cnt);    
		//将第i条线段加到线段树上,cnt是其状态,表示其是入边还是出边 
    }
    printf("%d\n",ans);
    return 0;
}

  

 

posted @ 2020-07-18 21:12  我微笑不代表我快乐  阅读(157)  评论(0编辑  收藏  举报