Description
JOI村有一片荒地,上面竖着N个稻草人,村民们每年多次在稻草人们的周围举行祭典。
有一次,JOI村的村长听到了稻草人们的启示,计划在荒地中开垦一片田地。和启示中的一样,田地需要满足以下条件:
田地的形状是边平行于坐标轴的长方形;
左下角和右上角各有一个稻草人;
田地的内部(不包括边界)没有稻草人。
给出每个稻草人的坐标,请你求出有多少遵从启示的田地的个数
Input
第一行一个正整数N,代表稻草人的个数
接下来N行,第i行(1<=i<=N)包含2个由空格分隔的整数Xi和Yi,表示第i个稻草人的坐标
Output
输出一行一个正整数,代表遵从启示的田地的个数
Sample Input
4
0 0
2 2
3 4
4 3
Sample Output
3
HINT
所有满足要求的田地由下图所示:
1<=N<=2*10^5
0<=Xi<=10^9(1<=i<=N)
0<=Yi<=10^9(1<=i<=N)
Xi(1<=i<=N)互不相同。
Yi(1<=i<=N)互不相同。
分析:
我们考虑对于每一个左下角的贡献,显然纵坐标小于他的点没有用。
我们先对横坐标排一个序,一个点的贡献就是删除掉纵坐标小于他的点,剩下点纵坐标的一个严格单调下降数列,因为只有这两个点中间的点的纵坐标都大于右上角的点的纵坐标,才有贡献。
考虑cdq分治,我们对每个位置维护一个
last[i]
l
a
s
t
[
i
]
,表示
i
i
这个点在当前区间,最右边的一个合法点的纵坐标。
我们先对当前分治区间的从大到小排序,对于一个位于左边的点,把纵坐标大于他的都插入一个单调栈里(显然合法的点构成单调),然后查询在
[last[i],a[i].y]
[
l
a
s
t
[
i
]
,
a
[
i
]
.
y
]
范围内右边的点有多少个,然后把纵坐标最小的更新
last
l
a
s
t
。
代码:
/**************************************************************
Problem: 4237
User: liangzihao
Language: C++
Result: Accepted
Time:15812 ms
Memory:8328 kb
****************************************************************/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define LL long long
const int maxn=2e5+7;
const int inf=1e9+7;
using namespace std;
int n,cnt,top;
int last[maxn];
LL ans;
struct node{
int x,y;
}a[maxn];
struct rec{
int x,y,k;
}sta[maxn];
struct data{
int y,k,size;
}b[maxn];
bool cmp(node a,node b)
{
return a.x<b.x;
}
bool cmp1(data a,data b)
{
return a.y>b.y;
}
int find(int x)
{
int k=20,t=1<<k,l=0;
while (k>=0)
{
if (l+t<=top)
{
if (sta[l+t].y>=x) l+=t;
}
k--,t/=2;
}
return l;
}
void solve(int l,int r)
{
if (l==r)
{
last[l]=inf;
return;
}
int mid=(l+r)/2;
solve(l,mid);
solve(mid+1,r);
cnt=top=0;
for (int i=l;i<=r;i++) b[++cnt]=(data){a[i].y,i,(i>mid)};
sort(b+1,b+cnt+1,cmp1);
for (int i=1;i<=cnt;i++)
{
if (b[i].size==0)
{
if ((sta[top].y<last[b[i].k]) && (top))
{
int d=find(last[b[i].k]);
ans+=(LL)top-(LL)d;
if (top!=d) last[b[i].k]=sta[top].y;
}
}
else
{
int k=b[i].k;
while ((top) && (sta[top].x>a[k].x)) top--;
sta[++top]=(rec){a[k].x,a[k].y,k};
}
}
}
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d%d",&a[i].x,&a[i].y);
sort(a+1,a+n+1,cmp);
solve(1,n);
printf("%lld",ans);
}