Thinking: Actually this problem can be solved in a violent way, which is not recommended. Here we made use of segment tree. The basic idea is to save the frequency(actually 0 or 1 for every number) of numbers. Sum in structure tree means "up till now, how many numbers have appear in this interval in total".
First we will use segment tree to calculate the first Minimum inversion number. Based on this , the following Minimum inversion number should be "previous + N-num[i]-num[i]-1".
The reason is that if you move the first number to the bottom of this sequence, "num[i]" pairs will lose, and in the meanwhile, "N-1-num[i]" pairs will be made.
AC code:
#include<iostream>
using namespace std;
#define maxn 5222
#define MIN(a,b) ((a)<(b)?(a):(b))
struct tree{
int l,r,Sum;
}node[maxn*2];
int sequence[maxn];
void build(int rt,int left,int right)
{
node[rt].l = left;
node[rt].r = right;
if(left == right)
return;
int mid = (left +right) >> 1;
build(rt << 1,left,mid);
build(rt << 1|1,mid+1,right);
}
void fix(int rt,int val)
{
if(node[rt].l > val ||node[rt].r < val) {
return;
}
if(node[rt].l == node[rt].r)
{
node[rt].Sum++;
return;
}
fix(rt << 1,val);
fix(rt << 1|1,val);
node[rt].Sum = node[rt<<1].Sum+node[rt<<1|1].Sum;
}
int query(int rt,int left,int right)
{
if(left > right)
return 0;
if(node[rt].r < left)
return 0;
if(node[rt].l >= left && node[rt].r <= right)
return node[rt].Sum;
if(node[rt].r == node[rt].l)
return node[rt].Sum;
return query(rt << 1,left,right)+query(rt << 1|1,left,right);
}
int main()
{
int N;
while(scanf("%d",&N)!=EOF)
{
memset(node,0,sizeof(node));
build(1,0,N-1);
int s = 0;
for(int i = 0;i < N;i++)
{
scanf("%d",&sequence[i]);
fix(1,sequence[i]);
s += query(1,sequence[i]+1,N-1);
}
int ans = s;
for(int i= 0;i < N;i++)
{
s += N-sequence[i]-sequence[i]-1;
ans = MIN(ans,s);
}
printf("%d\n",ans);
}
return 0;
}