题目: http://acm.hdu.edu.cn/showproblem.php?pid=1394
没看到多组输入,WA了一万次。。。。。。
其实很简单,有人暴力过得,我感觉归并排序、二叉排序树求逆序数都可以,但是我没写。
#include <stdio.h>
#include <string.h> const int MAXN = ; struct Tree_Node
{
int left, right;
int num;
} tree[MAXN<<]; void build(int left, int right, int step)
{
tree[step].left = left;
tree[step].right = right;
tree[step].num = ;
if(left == right)
return;
int mid = (left + right) >> ;
build(left, mid, step<<);
build(mid+, right, step<<|);
} void insert(int cur, int step)
{
if(cur >= tree[step].left && cur <= tree[step].right)
tree[step].num++;
if(tree[step].left == tree[step].right)
return;
int mid = (tree[step].left + tree[step].right) >> ;
if(cur <= mid)
insert(cur, step<<);
else
insert(cur, step<<|);
} int query(int left, int right, int step)
{
if(tree[step].left == left && tree[step].right == right)
{
return tree[step].num;
}
int mid = (tree[step].left + tree[step].right) >> ;
if(right <= mid)
{
return query(left, right, step<<);
}
else if(left > mid)
{
return query(left, right, step<<|);
}
else
{
return query(left, mid, step<<) + query(mid+, right, step<<|);
}
} int main()
{
int n, x[MAXN];
while(scanf("%d", &n) != EOF)
{
int ans = ;
build(, n, );
for(int i = ; i < n; i++)
{
scanf("%d", &x[i]);
ans += query(x[i]+, n, );
insert(x[i], );
}
int tmp = ans;
for(int i = ; i < n; i++)
{
tmp += n - x[i] - x[i] - ;
if(tmp < ans)ans = tmp;
}
printf("%d\n", ans);
}
return ;
}