The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.
For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:
a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)
You are asked to write a program to find the minimum inversion number out of the above sequences.
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10
1 3 6 9 0 8 5 7 4 2
Sample Output
16
题意:求一个不断变化的序列(变化规则为第一数字到最后)的最小逆序对数是多少 (i < j and ai > aj)
思路:树状数组,可以将原本序列的逆序数求得之后,把第一个数移到最后的逆序数是可以直接得到的。
比如原来的逆序数是ans,把a[i]移到最后后,减少逆序数a[i],同时增加逆序数n-a[i]-1个,就是ans-a[i]+n-a[i]-1;
因为数字为0----n-1所以数字整体要+1,达到数字本身和原数组的索引相对应的目的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
using namespace std;
const int MAXN=5050;
int c[MAXN];
int a[MAXN];
int n;
int lowbit(int x)
{
return x&(-x);
}
void add(int i,int val)
{
while(i<=n)
{
c[i]+=val;
i+=lowbit(i);
}
}
int sum(int i)
{
int s=0;
while(i>0)
{
s+=c[i];
i-=lowbit(i);
}
return s;
}
int main()
{
while(scanf("%d",&n)==1)
{
int ans=0;
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++){ //计算初始状态的逆序对
scanf("%d",&a[i]);
a[i]++; //+1处理
ans+=sum(n)-sum(a[i]); //计算当前数字的逆序对
add(a[i],1); //将该数组放入树状数组中
}
int re=ans;
for(int i=1;i<n;i++){ //可以省略最后一次变化
ans+=n-a[i]-(a[i]-1);
re=min(re,ans);
}
printf("%d\n",re);
}
return 0;
}