一个长度为n的序列 每次可以把第一个序列移动到最后 有n种 求这n种中逆序数最小的
首先可以用线段树求出一个序列的逆序数
从1到n如果b[i]是x 判断从x+1开始到n有多少个数比x大 就是x对应的逆序数 然后a[x]++ 反正就开个数组标记a[i]=1就代表有这个数 是按顺序标记的(越说越乱)
然后考虑如果把第一个拿到最后 因为他是第一个 所以听过他是x 那么对于x的逆序数有x对(0~x-1) 因为数字都是0-n-1的 如果把这个x移到最后 逆序数减少x对 增加了n-(x+1)
求出一种然后在循环n-1次求出所有的情况取最小
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 5010;
int a[maxn<<2];
int b[maxn];
void update(int l, int r, int rt, int x)
{
if(l == r)
{
a[rt]++;
return;
}
int m = (l + r) >> 1;
if(x <= m)
update(l, m, rt<<1, x);
else
update(m+1, r, rt<<1|1, x);
a[rt] = a[rt<<1] + a[rt<<1|1];
}
int query(int x, int y, int l, int r, int rt)
{
if(x == l && y == r)
return a[rt];
int m = (l + r) >> 1;
if(x > m)
return query(x, y, m+1, r, rt<<1|1);
else if(y <= m)
return query(x, y, l, m, rt<<1);
else
return query(x, m, l, m, rt<<1) + query(m+1, y, m+1, r, rt<<1|1);
}
int main()
{
int n;
while(scanf("%d", &n) == 1)
{
for(int i = 1; i <= n; i++)
scanf("%d", &b[i]);
memset(a, 0, sizeof(a));
int ans = 0;
for(int i = 1; i <= n; i++)
{
int temp = query(b[i]+1, n, 1, n, 1);
//printf("%d\n", temp);
ans += temp;
update(1, n, 1, b[i]+1);
}
int res = ans;
for(int i = 1; i < n; i++)
{
ans = ans - b[i] + n - b[i] - 1;
//printf("%d\n", ans);
res = min(ans, res);
}
printf("%d\n", res);
}
return 0;
}
树状数组也可以统计逆序数
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 5010;
int a[maxn];
int C[maxn];
int n;
int lowbit(int x)
{
return x & -x;
}
void add(int x)
{
while(x <= n)
{
C[x]++;
x += lowbit(x);
}
}
int sum(int x)
{
int ret = 0;
while(x > 0)
{
ret += C[x];
x -= lowbit(x);
}
return ret;
}
int main()
{
while(scanf("%d", &n) == 1)
{
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
memset(C, 0, sizeof(C));
int ans = 0;
for(int i = n; i >= 1; i--)
{
int temp = sum(a[i]+1);
ans += temp;
add(a[i]+1);
}
int res = ans;
for(int i = 1; i < n; i++)
{
ans = ans - a[i] + n - a[i] - 1;
res = min(ans, res);
}
printf("%d\n", res);
}
return 0;
}