Description
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
线段树,一个叶子表示这个数字组成的逆序个数有多少个;一个节点表示这个区间的所有数字的逆序个数多少个,先计算出当前的逆序个数,然后通过公式计算逆序个数的公示来改变位置计算,最后求出最小值;
代码:
#include <iostream>
#include <cstdio>
#include<cstring>
#include<algorithm>
#define MAX 5005
using namespace std;
int que[MAX];
int test;
int tree[MAX<<2];
/*
void build ( int p,int l, int r )
{
if ( l == r ){ tree[p] = que[l]; return ; }
int mid = ( l + r ) >> 1;
build ( p * 2, l , mid );
build ( p * 2 + 1, mid + 1, r );
}*/
int finds ( int p, int l,int r, int sl,int sr)///找出没有改变的逆序数列的逆序对数;
{
if ( l == r )
{
for ( int i = l + 1; i <= sr; i++ )
{
if ( que[i] < que[l])
tree[p]++;
}
return tree[p];
}
int mid = ( r + l ) >> 1;
tree[p] = finds( 2 * p, l, mid, sl, sr ) + finds( 2 * p + 1, mid + 1, r, sl, sr );
return tree[p];
}
/*
int change(int p, int l, int r, int i)
{
if ( l == r )
{
if ( l == i )
{
tree[p] = 0;
return tree[p];
}
else
{
if ( que[l] > que[i] )
tree[p]++;
return tree[p];
}
}
int mid = ( l + r ) >> 1;
tree[p] = change(2 * p, l, mid, i) + change(2*p+1, mid+1, r, i );
return tree[p];
}*/
int main()
{
//freopen("in.txt","r",stdin);
while ( cin >> test )
{
memset(tree, 0, sizeof(tree));
for ( int i = 0; i < test; i++ )
{
scanf("%d",&que[i]);
}
int len = test - 1;
int ans ;
ans = finds(1,0,len,0,len);
int ans1 = ans;
for ( int i = 0; i < test; i++)
{
//cout << i << " " << change(1,i,i+len,i) << endl;
ans1 += len- 2*que[i];///求逆序的个数公式;搜一遍的话超时妥妥的
ans = min(ans,ans1);
}
printf("%d\n",ans);
}
}