ZOJ 3129 || POJ 3067 Japan

同POJ 2299 也是利用树状数组求逆序数的应用

将x从大到小排序,若x相同,按y从大到小排序,对y建立树状数组,根据逆序数的定义,画图演算一遍就很清楚了

  
    
#include < stdio.h >
#include
< stdlib.h >
#include
< string .h >
#define MAXN 1001
struct Pair{
int x, y;
}p[
1000010 ];
int n, m, k;
int c[MAXN];

int cmp( const void * a, const void * b){
if (((Pair * )a) -> x == ((Pair * )b) -> x)
return ((Pair * )b) -> y - ((Pair * )a) -> y;
return ((Pair * )b) -> x - ((Pair * )a) -> x;
}
inline
int lowbit( int t){
return t & ( - t);
}
void update( int i){
while (i <= m){
c[i]
+= 1 ; // 增量为1
i += lowbit(i);
}
}
int getsum( int i){
int sum = 0 ;
while (i > 0 ){
sum
+= c[i];
i
-= lowbit(i);
}
return sum;
}
int main(){
int T, t = 0 ;
scanf(
" %d " , & T);
while ( T -- ){
scanf(
" %d%d%d " , & n, & m, & k);
for ( int i = 1 ; i <= k; ++ i){
scanf(
" %d%d " , & p[i].x, & p[i].y);
}
qsort(p
+ 1 , k, sizeof (p[ 0 ]), cmp);
long long ans = 0 ;
for ( int i = 1 ; i <= k; ++ i){
ans
+= getsum(p[i].y - 1 );
update(p[i].y);
}
printf(
" Test case %d: %lld\n " , ++ t, ans);
memset(c,
0 , sizeof (c));
}
return 0 ;
}

你可能感兴趣的:(poj)