题目大意
给定平面内的 n 个点,求有多少个矩形,左下角是一个点,右上角是一个点,且内部没有其他点。
Data Constraint
题解
考虑分治,先将点按
x
从小到大排序。
假设当前分治区间为
现在要求以左边区间的点为左下角,右边区间为右上角的答案。于是将点按照
y
从大到小排序,然后右边维护一个
时间复杂度:
SRC
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std ;
#define N 200000 + 10
typedef long long ll ;
const int MAXN = 19 ;
struct Point {
int x , y ;
Point ( int X = 0 , int Y = 0 ) { x = X , y = Y ; }
} P[N] , tp[N] , S1[N] , S2[N] ;
int n ;
ll ans ;
bool cmp( Point a , Point b ) { return a.x < b.x ; }
int Search( int m , int st , int ed ) {
int l = 1 , r = m , x = m + 1 , y = 0 ;
while ( l <= r ) {
int mid = (l + r) / 2 ;
if ( S1[mid].y <= st ) r = mid - 1 , x = mid ;
else l = mid + 1 ;
}
l = 1 , r = m ;
while ( l <= r ) {
int mid = (l + r) / 2 ;
if ( S1[mid].y >= ed ) l = mid + 1 , y = mid ;
else r = mid - 1 ;
}
return y - x + 1 ;
}
void DIV( int l , int r ) {
if ( l == r ) return ;
int mid = (l + r) / 2 ;
int st = P[mid].x ;
DIV( l , mid ) ;
DIV( mid + 1 , r ) ;
int Cnt = 0 , h1 = l , h2 = mid + 1 ;
while ( h1 <= mid || h2 <= r ) {
Point tmp1 = ( h1 <= mid ? P[h1] : Point( -1 , -1 ) ) ;
Point tmp2 = ( h2 <= r ? P[h2] : Point( -1 , -1 ) ) ;
if ( tmp1.y > tmp2.y ) tp[++Cnt] = tmp1 , h1 ++ ;
else tp[++Cnt] = tmp2 , h2 ++ ;
}
int top1 = 0 , top2 = 0 ;
S2[0].y = 0x7FFFFFFF ;
for (int i = l ; i <= r ; i ++ ) {
P[i] = tp[i-l+1] ;
if ( P[i].x > st ) {
while ( top1 && S1[top1].x > P[i].x ) top1 -- ;
S1[++top1] = P[i] ;
} else {
while ( top2 && S2[top2].x < P[i].x ) top2 -- ;
S2[++top2] = P[i] ;
ans += Search( top1 , S2[top2-1].y - 1 , S2[top2].y + 1 ) ;
}
}
}
int main() {
freopen( "scarecrows.in" , "r" , stdin ) ;
freopen( "scarecrows.out" , "w" , stdout ) ;
scanf( "%d" , &n ) ;
for (int i = 1 ; i <= n ; i ++ ) scanf( "%d%d" , &P[i].x , &P[i].y ) ;
sort( P + 1 , P + n + 1 , cmp ) ;
DIV( 1 , n ) ;
printf( "%lld\n" , ans ) ;
return 0 ;
}
以上.