SGU 180

题型:求逆序数,(用树状数组+离散化)

心得:很悲剧,TLE AT #31 N 次,原因出在qsort(),(难怪发现不了),后来改sort(),就过了。看来qsort()的效率还有待分析!

代码
   
     
#include < stdio.h >
#include
< stdlib.h >
#include
< string .h >
#define NL 65538
#define LL __int64

struct Num {
int v, no;
}a[NL];
int n, b[NL], mx;
int t[NL];

int cmp( const void * a, const void * b)
{
return (( struct Num * )a) -> v - (( struct Num * )b) -> v;
}

inline
int lowbit( int k)
{
return k & ( - k);
}

int sum( int k)
{
int cnt = 0 ;
while (k > 0 ) {
cnt
+= t[k];
k
-= lowbit(k);
}
return cnt;
}

void update( int k, int c)
{
while (k <= mx) {
t[k]
+= c;
k
+= lowbit(k);
}
}

int main()
{
int i, p;
LL cnt;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf( " %d " , & n);
for (i = 0 ; i < n; i ++ ) {
scanf(
" %d " , & a[i].v);
a[i].no
= i;
}
qsort(a, n,
sizeof (a[ 0 ]), cmp);
p
= 1 ;
b[a[
0 ].no] = 1 ;
for (i = 1 ; i < n; i ++ ) {
if (a[i].v != a[i - 1 ].v) p ++ ;
b[a[i].no]
= p;
}
mx
= p;
memset(t,
0 , sizeof (t));
cnt
= 0 ;
for (i = n - 1 ; i >= 0 ; i -- ) {
cnt
+= sum(b[i] - 1 );
update(b[i],
1 );
}
printf(
" %I64d\n " , cnt);
return 0 ;

}

 

你可能感兴趣的:(SGU 180)