题目:http://acm.hdu.edu.cn/showproblem.php?pid=1394
通过这道题学到的新东西:
(1)用树状数组来求逆序对数
(2)将0~N-1的permutation进行左移一位,即a[0]移到最后,逆序对数首先会减少a[0](a[0]是0~N-1的一个数,当a[0]是x时,说明0~x-1在其后面,有x个,所以a[0]的逆序对数是a[0],因为a[0]被移到最后,所以这些逆序对消失了),接着逆序对数还会增加n-1-a[0](当a[0]是x时,说明x+1~n-1在x前面,有n-1-x个,所以a[0]被移到最后时,增加了这些逆序对)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, a[5000], c[5001] = {0};
inline int lowbit(int x){ return x & -x; }
void add(int x, int d)
{
for(; x <= n; x += lowbit(x)) c[x] += d;
}
int sum(int x)
{
int s = 0;
for(; x; x -= lowbit(x)) s += c[x];
return s;
}
int getReversePair()
{
//initialize
memset(c + 1, 0, n << 2);
//build tree array
int i = 0, x, total = 0;
for(; i < n; ++i){
x = a[i] + 1;
add(x, 1);
total += x - sum(x);
}
return total;
}
int main()
{
int i, pair, tmp;
while(scanf("%d", &n) == 1){
for(i = 0; i < n; ++i) scanf("%d", &a[i]);
tmp = pair = getReversePair();
for(i = 0; i < n; ++i){
tmp += -a[i] + (n - 1 - a[i]);
pair = min(pair, tmp);
}
printf("%d\n", pair);
}
return 0;
}