There's a beach in the first quadrant. And from time to time, there are sea waves. A wave ( xx , yy ) means the wave is a rectangle whose vertexes are ( 00 , 00 ), ( xx , 00 ), ( 00 , yy ), ( xx , yy ). Every time the wave will wash out the trace of former wave in its range and remain its own trace of ( xx , 00 ) -> ( xx , yy ) and ( 00 , yy ) -> ( xx , yy ). Now the toad on the coast wants to know the total length of trace on the coast after n waves. It's guaranteed that a wave will not cover the other completely.
Input
The first line is the number of waves n(n \le 50000)n(n≤50000).
The next nn lines,each contains two numbers xx yy ,( 0 < x0<x , y \le 10000000y≤10000000 ),the ii-th line means the ii-th second there comes a wave of ( xx , yy ), it's guaranteed that when 1 \le i1≤i , j \le nj≤n ,x_i \le x_jxi≤xj and y_i \le y_jyi≤yj don't set up at the same time.
Output
An Integer stands for the answer.
Hint:
As for the sample input, the answer is 3+3+1+1+1+1=103+3+1+1+1+1=10
样例输入复制
3 1 4 4 1 3 3
样例输出复制
10
题目来源
题意:
有一个沙滩,每个波浪都是一个矩形的左下角为(0,0),右上角为(x,y)。每一次波浪都会冲刷掉之前留下来的痕迹,问最后留下来的痕迹是多长。
思路:
可以想到最后算出的值是一个宽度加上一个高度,所以可以分别求出这两个值相加。
讨论其中的宽度:
如果时间正好是升序,高度正好是降序排序,那么每一次都把宽度累加就是最后的答案,我们可以先把高度按照降序排序。排序后不能保证时间是升序的,那么时间大的可以覆盖掉时间小的。但是在高度是降序的排序的情况下只能是排序后在前面的并且时间还大于当前的波浪的时间,当前波浪才会被覆盖掉。
鉴于这点我们需要知道比当前波浪高度高的并且时间大于当前波浪的最长的宽度,所以我们建一个以时间为下标的线段树。
如果查询发现当前波浪比查询到的最大值仍然大,那么就加上这个值。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define lson i<<1,l,mid
#define rson i<<1|1,mid+1,r
using namespace std;
typedef long long ll;
const int maxn=5e4+5;
int tr[maxn*4];
struct node
{
int w,h,id;
}q[maxn];
bool cmp1(node a,node b)//按宽度排序
{
return a.w>b.w;
}
bool cmp2(node a,node b)//按高度排序
{
return a.h>b.h;
}
void pushup(int i)
{
tr[i]=max(tr[2*i],tr[2*i+1]);
}
void build(int i,int l,int r)
{
tr[i]=0;
if(l==r)
{
return;
}
int mid=(l+r)/2;
build(lson);
build(rson);
}
void update(int i,int l,int r,int x,int c)
{
if(l==r&&l==x)
{
tr[i]=c;
return;
}
int mid=(l+r)/2;
if(x<=mid) update(lson,x,c);
else update(rson,x,c);
pushup(i);
}
int query(int i,int l,int r,int x,int y)
{
int ans=0;
if(x<=l&&r<=y)
{
return tr[i];
}
int mid=(l+r)/2;
if(x<=mid) ans=max(ans,query(lson,x,y));
if(y>mid) ans=max(ans,query(rson,x,y));
return ans;
}
int main()
{
int n;
ll ans=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&q[i].w,&q[i].h);
q[i].id=i;
}
sort(q+1,q+1+n,cmp1);//按宽度排序
build(1,1,n);
for(int i=1;i<=n;i++)
{
int num=query(1,1,n,q[i].id,n);
if(q[i].h>num)
{
ans+=q[i].h-num;
}
update(1,1,n,q[i].id,q[i].h);
}
build(1,1,n);
sort(q+1,q+1+n,cmp2);//按高度排序
for(int i=1;i<=n;i++)
{
int num=query(1,1,n,q[i].id,n);
if(q[i].w>num)
{
ans+=q[i].w-num;
}
update(1,1,n,q[i].id,q[i].w);
}
printf("%lld\n",ans);
return 0;
}