Description
JOI村有一片荒地,上面竖着N个稻草人,村民们每年多次在稻草人们的周围举行祭典。
有一次,JOI村的村长听到了稻草人们的启示,计划在荒地中开垦一片田地。和启示中的一样,田地需要满足以下条件:
田地的形状是边平行于坐标轴的长方形;
左下角和右上角各有一个稻草人;
田地的内部(不包括边界)没有稻草人。
给出每个稻草人的坐标,请你求出有多少遵从启示的田地的个数。
Solution
考虑分治,每次分成上下两部分,考虑上半边部分的贡献,用单调栈维护,每次查询时二分即可。
Source
/************************************************
* Au: Hany01
* Date: Mar 15th, 2018
* Prob: BZOJ4237
* Email: hany01@foxmail.com
************************************************/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define fir first
#define sec second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) ((int)(a).size())
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define Mod (1000000007)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia
template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }
inline int read()
{
register int _, __; register char c_;
for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
return _ * __;
}
inline void File()
{
#ifdef hany01
freopen("bzoj4237.in", "r", stdin);
freopen("bzoj4237.out", "w", stdout);
#endif
}
const int maxn = 200005;
struct Data { int x, y; };
inline bool cmp1(const Data& A, const Data& B){ return A.y != B.y ? A.y < B.y : A.x < B.x; }
inline bool cmp2(const Data& A, const Data& B){ return A.x != B.x ? A.x < B.x : A.y < B.y; }
Data stk1[maxn], stk2[maxn], A[maxn];
int top1, top2, n;
LL Ans;
inline void BS(Data p)
{
if (p.x < stk2[top2].x) return ;
register int l = 1, r = top2, mid;
while (l < r) {
mid = (l + r) >> 1;
if (p.x > stk2[mid].x) r = mid; else l = mid + 1;
}
Ans += top2 - l + 1;
}
void CDQ(int l, int r)
{
if (l == r) return ;
register int mid = (l + r) >> 1;
CDQ(l, mid), CDQ(mid + 1, r);
sort(A + l, A + mid + 1, cmp2), sort(A + mid + 1, A + r + 1, cmp2);
int x = mid, y = r;
top2 = 0;
stk1[top1 = 1] = (Data){INF, INF};
while (x >= l) {
while (y > mid && A[y].x > A[x].x) {
Data p = A[y];
while (top2 && p.y < stk2[top2].y) -- top2;
stk2[++ top2] = p;
-- y;
}
Data p = A[x --];
while (top1 && p.y > stk1[top1].y) -- top1;
stk1[++ top1] = p;
BS(stk1[top1 - 1]);
}
}
int main()
{
File();
n = read();
For(i, 1, n) A[i].x = read(), A[i].y = read();
sort(A + 1, A + 1 + n, cmp1);
CDQ(1, n);
printf("%lld\n", Ans);
return 0;
}