题目描述
Minimum Inversion Number
解法:树状数组(C++)
#include <bits/stdc++.h>
using namespace std;
const int N = 5005;
int c[N];
int a[N];
int lowbit(int x){return x&(-x);}
void update(int x)
{
while(x<N)
{
c[x]++;
x += lowbit(x);
}
}
int sum(int x)
{
int s = 0;
while(x>0)
{
s += c[x];
x -= lowbit(x);
}
return s;
}
int main()
{
int n;
while(~scanf("%d", &n))
{
memset(c, 0, sizeof(c));
int cnt = 0;
for(int i=1;i<=n;i++)
{
scanf("%d", &a[i]);
a[i]++;
cnt += sum(N-1)-sum(a[i]);
update(a[i]);
}
int mmin = INT_MAX;
for(int i=1;i<=n;i++)
{
cnt = cnt-(a[i]-1)+(n-a[i]);
mmin = min(mmin, cnt);
}
printf("%d\n", mmin);
}
return 0;
}