树状数组求逆序数的模板

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define lowbit(x) x&(-x)
int res[1000005] , tree[1000005] ;

struct num{
    int val,pos;
}m[1000005];

bool cmp (num a, num b){
    return a.val<b.val;
}

void plus ( int x ,int n ){        //树状数组储存法
    while( x <= n ){
        tree[x] ++;
        x += lowbit(x);
    }
}

int SUM ( int x ){               //树状数组的部分了
    int s = 0;
    while(x){
        s += tree[x];
        x -= lowbit(x) ;
    }
    return s;
}
int main(){
    int n , x , a , b ;
    while( ~scanf( "%d" , &n ) )
    {
        memset( m , 0 , sizeof(m) );
        memset( res , 0 , sizeof(res) );
        memset( tree , 0 , sizeof(tree) );
        for( int i = 1 ; i <= n ; i++ ){
            scanf( "%d" , &x );
            m[i].val = x ;
            m[i].pos = i ;
        }
        sort( m+1 , m+n+1 , cmp );
        for( int i = 1 ; i <= n ; i++ ){     //离散化
            res[m[i].pos] = i ;
        }
        __int64 sum = 0;
        for( int i = 1 ; i <= n ; i++ ){
            plus( res[i] , n );
            sum += ( i - SUM( res[i]-1 ) - 1) ;
        }
        printf("%I64d\n",sum);
    }
    return 0;
}

你可能感兴趣的:(struct,tree)