传送门:【COGS】1752. [BOI2007]摩基亚Mokia
题目分析:cdq分治的基本运用。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
typedef long long LL ;
#define rep( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i )
#define For( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define rev( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define clr( a , x ) memset ( a , x , sizeof a )
#define ls ( o << 1 )
#define rs ( o << 1 | 1 )
#define lson l , m
#define rson m + 1 , r
#define root 1 , 1 , cnt
#define mid ( ( l + r ) >> 1 )
const int MAXN = 200005 ;
struct Node {
int x1 , x2 , y , f , idx ;
Node () {}
Node ( int x1 , int x2 , int y , int f , int idx ) : x1 ( x1 ) , x2 ( x2 ) , y ( y ) , f ( f ) , idx ( idx ) {}
bool operator < ( const Node& a ) const {
if ( y != a.y ) return y < a.y ;
return idx < a.idx ;
}
} ;
Node q[MAXN << 1] , s1[MAXN << 1] , s2[MAXN << 1] ;
int m ;
int a[MAXN << 1] , cnt ;
int T[MAXN << 1] ;
int ans[MAXN] , query ;
int n ;
int unique ( int n ) {
int cnt = 1 ;
sort ( a + 1 , a + n + 1 ) ;
For ( i , 2 , n ) if ( a[i] != a[cnt] ) a[++ cnt] = a[i] ;
return cnt ;
}
int hash ( int x , int l = 1 , int r = cnt ) {
while ( l < r ) {
int m = mid ;
if ( a[m] >= x ) r = m ;
else l = m + 1 ;
}
return l ;
}
void add ( int x , int v ) {
for ( int i = x ; i <= cnt ; i += i & -i ) T[i] += v ;
}
int sum ( int x , int ans = 0 ) {
for ( int i = x ; i > 0 ; i -= i & -i ) ans += T[i] ;
return ans ;
}
void cdq ( int l , int r ) {
if ( r <= l ) return ;
int m = mid , top1 = 0 , top2 = 0 , j = 0 ;
cdq ( lson ) ;
cdq ( rson ) ;
For ( i , m + 1 , r ) if ( q[i].idx ) s1[top1 ++] = q[i] ;
For ( i , l , m ) if ( !q[i].idx ) s2[top2 ++] = q[i] ;
sort ( s1 , s1 + top1 ) ;
sort ( s2 , s2 + top2 ) ;
rep ( i , 0 , top1 ) {
while ( j < top2 && s2[j].y <= s1[i].y ) {
add ( s2[j].x1 , s2[j].f ) ;
++ j ;
}
ans[s1[i].idx] += s1[i].f * sum ( s1[i].x2 ) ;
ans[s1[i].idx] -= s1[i].f * sum ( s1[i].x1 - 1 ) ;
}
rep ( i , 0 , j ) add ( s2[i].x1 , -s2[i].f ) ;
}
void scanf ( int& x , char c = 0 ) {
while ( ( c = getchar () ) < '0' ) ;
x = c - '0' ;
while ( ( c = getchar () ) >= '0' ) x = ( x << 1 ) + ( x << 3 ) + c - '0' ;
}
void solve () {
int op , x1 , y1 , x2 , y2 , w ;
m = cnt = query = 0 ;
while ( 1 ) {
scanf ( "%d" , &op ) ;
if ( op == 3 ) break ;
if ( op == 1 ) {
scanf ( "%d%d%d" , &x1 , &y1 , &w ) ;
q[++ m] = Node ( x1 , x1 , y1 , w , 0 ) ;
a[++ cnt] = x1 ;
} else {
scanf ( "%d%d%d%d" , &x1 , &y1 , &x2 , &y2 ) ;
q[++ m] = Node ( x1 , x2 , y2 , 1 , ++ query ) ;
q[++ m] = Node ( x1 , x2 , y1 - 1 , -1 , query ) ;
a[++ cnt] = x2 ;
a[++ cnt] = x1 - 1 ;
}
}
cnt = unique ( cnt ) ;
For ( i , 1 , m ) {
if ( !q[i].idx ) q[i].x1 = hash ( q[i].x1 ) ;
else {
q[i].x1 = hash ( q[i].x1 - 1 ) + 1 ;
q[i].x2 = hash ( q[i].x2 ) ;
}
}
cdq ( 1 , m ) ;
For ( i , 1 , query ) printf ( "%d\n" , ans[i] ) ;
}
int main () {
freopen ( "mokia.in" , "r" , stdin ) ;
freopen ( "mokia.out" , "w" , stdout ) ;
while ( ~scanf ( "%*d%d" , &n ) ) solve () ;
return 0 ;
}