hdu 1394 inversion number ++ARRAY TREE

求逆序数



#include <stdio.h>
#include <string.h>

#define N 5050

int a[N],n;
int lowbit(int i)
{
    return i&(-i);
}
void add(int i)
{
    for(;i<=n; i += lowbit(i))
        a[i] ++;
}
int sum(int i)
{
    int s = 0;
    for(; i > 0; i -= lowbit(i))
        s += a[i];
    return s;
}
int main()
{
    while(scanf("%d",&n)!= EOF)
    {
        int i,res = 0,b[N];
        memset(a,0,sizeof(a));
        for(i = 0; i < n; ++i)
        {
            scanf("%d",&b[i]);
            ++b[i];
            res += sum(n) - sum(b[i]);
            add(b[i]);
        }
        int tmp = res;
        ///新的逆序数只由移动的最左端的数决定
        for(i = 0; i < n; ++i)
        {
            tmp = tmp + sum(n) - sum(b[i]) -sum(b[i] - 1);
            if(tmp < res)
                res = tmp;
        }
        printf("%d\n",res);
    }
    return 0;
}


你可能感兴趣的:(hdu 1394 inversion number ++ARRAY TREE)