hdu 2689 逆序数对

本题:求逆序数对的个数,用树状数组可求,将每个值赋成1,i-query(x)就是x这个数的逆序对数,也就是前面有几个比我大的数。

#include <iostream>

#include <stdio.h>

#include <cstring>

using namespace std;

const int  maxn=1008;

int tree[maxn];

int lowbit(int t)

{     return t & (-t); }

void update(int pos,int val)

{    

while(pos<=maxn)  

   {        

tree[pos]+=val;        

pos+=lowbit(pos);

    }

}

int query(int pos)

{

    int sum=0;    

while(pos>0)    

{         sum+=tree[pos];  

       pos-=lowbit(pos);

    }   

  return sum;

}

int main()

{ int n,x,ans=0;

while(cin>>n)

{     ans=0;  

   memset(tree,0,sizeof(tree));  

   for(int i=1;i<=n;i++)   

  {         scanf("%d",&x);  

       update(x,1);        

ans+=i-query(x);

    }    

printf("%d\n",ans);

 

}

    //cout << "Hello world!" << endl;     return 0; }

posted @ 2012-09-23 07:32  兴安黑熊  阅读(205)  评论(0编辑  收藏  举报