n个数的排列,一个数a[i](0 <= a[i] < n),它在这个排列中,大于它的数有n - a[i] - 1个,小于它的数有a[i]个,将它放到最后,大于它的数变为逆序,小于它的数变为顺序,逆序数 = 变化前的逆序数 + n - a[i] - 1 - a[i].
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cctype>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
class ST
{
private:
int n, a[5005], b[5005 * 4], ans, inv;
public:
void pushup(int rt)
{
b[rt] = b[rt << 1] + b[rt << 1 | 1];
}
void build(int _l, int _r, int rt)
{
b[rt] = 0;
if (_l == _r)
return ;
int m = _l + (_r - _l) / 2;
build(_l, m, rt << 1);
build(m + 1, _r, rt << 1 | 1);
}
void update(int p, int _l, int _r, int rt)
{
if (_l == _r)
{
b[rt]++;
return ;
}
int m = _l + (_r - _l) / 2;
if (p <= m)
update(p, _l, m, rt << 1);
else
update(p, m + 1, _r, rt << 1 | 1);
pushup(rt);
}
int query(int L, int R, int _l, int _r, int rt)
{
if (_l <= L && _r >= R)
return b[rt];
int m = L + (R - L) / 2;
int ret = 0;
if (_l <= m)
ret += query(L, m, _l, _r, rt << 1);
if (_r > m)
ret += query(m + 1, R, _l, _r, rt << 1 | 1);
return ret;
}
bool Input()
{
if (~scanf("%d", &n))
{
inv = 0;
build(0, n - 1, 1);
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
inv += query(0, n - 1, a[i], n - 1, 1);
update(a[i], 0, n - 1, 1);
}
return true;
}
return false;
}
void Output()
{
ans = inv;
for (int i = 0; i < n; i++)
{
inv += n - a[i] - 1 - a[i];
ans = min(ans, inv);
}
printf("%d\n", ans);
}
} stree;
int main()
{
while (stree.Input())
stree.Output();
return 0;
}