There's a beach in the first quadrant. And from time to time, there are sea waves. A wave ( xxx , yyy ) means the wave is a rectangle whose vertexes are ( 000 , 000 ), ( xxx , 000 ), ( 000 , yyy ), ( xxx , yyy ). Every time the wave will wash out the trace of former wave in its range and remain its own trace of ( xxx , 000 ) -> ( xxx , yyy ) and ( 000 , yyy ) -> ( xxx , yyy ). 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≤50000)n(n \le 50000)n(n≤50000).
The next nnn lines,each contains two numbers xxx yyy ,( 0<x0 < x0<x , y≤10000000y \le 10000000y≤10000000 ),the iii-th line means the iii-th second there comes a wave of ( xxx , yyy ), it's guaranteed that when 1≤i1 \le i1≤i , j≤nj \le nj≤n ,xi≤xjx_i \le x_jxi≤xj and yi≤yjy_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=103+3+1+1+1+1=10
样例输入
3 1 4 4 1 3 3
样例输出
10
题目来源
解题思路:三维偏序问题(时间,x,y),转化为二维(时间为有序),用线段树,将其排序,排序方法为:将x和y分别来看,对x进行计算的时候,由于当前矩形要考虑之后的矩形将当前矩形覆盖多少,所以要逆序,先把后面出现的矩形输入线段树(以y作为划分标准,里面存的值为x),然后对于当前出现的矩形找到已经在线段树中的在(y【i】,ymax)之间的x最大值,用当前矩形的x【i】-x区间最大值,得到的结果为该矩形x值对最终结果的贡献值,对于y值也是如此
#include <iostream>
#include <bits/stdc++.h>
#include <time.h>
#define inf 0x3f3f3f3f
using namespace std;
struct node
{
int l,r;
int Max;
} tree[9000000];
void build(int i,int l,int r)
{
tree[i].l=l;
tree[i].r=r;
if(l==r)
{
tree[i].Max=0;
return ;
}
int mid=(l+r)>>1;
build(i<<1,l,mid);
build(i<<1|1,mid+1,r);
tree[i].Max=max(tree[i<<1].Max,tree[i<<1|1].Max);
}
int Find(int i,int l,int r)
{
if(tree[i].l==l&&tree[i].r==r) return tree[i].Max;
int mid=(tree[i].l+tree[i].r)>>1;
int ans=0;
if(r<=mid) ans=Find(i<<1,l,r);
else if(l>mid) ans=Find(i<<1|1,l,r);
else
{
ans=max(Find(i<<1,l,mid),Find(i<<1|1,mid+1,r));
}
return ans;
}
void add(int i,int t,int s)
{
tree[i].Max=max(tree[i].Max,s);
if(tree[i].l==tree[i].r)return;
int mid=(tree[i].l+tree[i].r)>>1;
if(t<=mid)add(i<<1,t,s);
else add(i<<1|1,t,s);
}
int cmp(int a,int b)
{
return a<b;
}
int lisan(int * y,int n)
{
sort(y+1,y+1+n,cmp);
return unique(y+1,y+n+1)-y-1;
}
int getid(int *y,int x,int n)
{
return lower_bound(y+1,y+1+n,x)-y;
}
int x[100000],y[100000];
int xx[100000],yy[100000];
int main()
{
int n;
scanf("%d",&n);
int x_Max,y_Max;
for(int i=1; i<=n; i++)
{
scanf("%d %d",&x[i],&y[i]);
xx[i]=x[i];
yy[i]=y[i];
}
long long int ans=0;
y_Max=lisan(yy,n);
x_Max=lisan(xx,n);
build(1,1,y_Max);
for(int i=n; i>=1; i--)
{
ans+=(long long int)(x[i]-Find(1,getid(yy,y[i],y_Max),y_Max));
add(1,getid(yy,y[i],y_Max),x[i]);
}
build(1,1,x_Max);
for(int i=n; i>=1; i--)
{
ans+=(long long int)(y[i]-Find(1,getid(xx,x[i],x_Max),x_Max));
add(1,getid(xx,x[i],x_Max),y[i]);
}
printf("%lld\n",ans);
return 0;
}