暴力可以过,算初始逆序数的时候可以用线段树优化。通过递推关系可以求得各序列的逆序数。
/****************************************************/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <stack>
#include <map>
#include <queue>
#include <algorithm>
#include <ctime>
#define EPS 1E-8
#define MAXN 5010
#define INF (~0U >> 2)
#define MOD 10007
#define Lson l, mid, rt << 1
#define Rson mid + 1, r, rt << 1 | 1
using namespace std;
typedef long long LL;
/****************************************************/
int sum[MAXN << 2], a[MAXN];
void push_up(int rt)
{
sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}
void build(int l, int r, int rt)
{
if (l == r)
{
sum[rt] = 0;
return;
}
int mid = (l + r) >> 1;
build(Lson);
build(Rson);
push_up(rt);
}
void update(int p, int l, int r, int rt)
{
if (l == r)
{
sum[rt]++;
return;
}
int mid = (l + r) >> 1;
if (p <= mid)
update(p, Lson);
else
update(p, Rson);
push_up(rt);
}
int query(int L, int R, int l, int r, int rt)
{
if (L <= l && r <= R)
{
return sum[rt];
}
int mid = (l + r) >> 1, ret = 0;
if (L <= mid) ret += query(L, R, Lson);
if (R > mid) ret += query(L, R, Rson);
return ret;
}
int main()
{
int N;
while (scanf("%d", &N) != EOF)
{
build(0, N - 1, 1);
int sum = 0;
for (int i = 0; i < N; i++)
{
scanf("%d", &a[i]);
sum += query(a[i], N - 1, 0, N - 1, 1);
update(a[i], 0, N - 1, 1);
}
int ans = sum;
for (int i = 0; i < N; i++)
{
sum += (N - a[i] - 1) - a[i];
ans = min(sum, ans);
}
printf("%d\n", ans);
}
}