题目:
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>
using namespace std;
#define MAX 5010
int sum[MAX << 2],a[MAX];
void pushup(int rt) {sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];}
void build(int rt,int l,int r)
{
sum[rt] = 0;
if(l == r) return;
int mid = (l + r) >> 1;
build(rt << 1,l,mid);
build(rt << 1 | 1,mid + 1,r);
pushup(rt);
}
void update(int c,int l,int r,int rt)
{
if(l == r){
sum[rt]++;
return;
}
int mid = (l + r) >> 1;
if(c <= mid) update(c,l,mid,rt << 1);
else update(c,mid + 1,r,rt << 1 | 1);
pushup(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;
int sum = 0;
if(L <= mid) sum += query(L,R,l,mid,rt << 1);
if(R > mid) sum += query(L,R,mid + 1,r,rt << 1 | 1);
return sum;
}
int main()
{
int n,minx;
while(~scanf("%d",&n)){
build(1,1,n);
int sum = 0;
for(int i = 1;i <= n;i++) cin >> a[i];
for(int i = 1;i <= n;i++){ //计算逆序数
sum += query(a[i] + 1,n,1,n,1);
update(a[i] + 1,1,n,1);
}
minx = sum;
for(int i = 1;i <= n;i++){
sum += (n - 2 * a[i] - 1);
minx = min(minx,sum);
}
cout << minx << endl;
}
return 0;
}
题意:
给你n个数,每次变换都把第一个数放到最后一位上,问你在这些变化中逆序数最小是多少。
思路:
首先我们要求出初始序列的逆序数(逆序数的相关博客可参照这位大佬的博客:http://www.cnblogs.com/MingSD/p/8387345.html)
求出初始序列的逆序数后,我们要来考虑如何去求移位之后序列的逆序数。这里来举个例子:
3,4,1,2,0 这5个数逆序数是8,移位之后变为:4,1,2,0,3此时逆序数为6。在移位过程中我们发现1,2,0这四个数相对位置是不变的,所以他们的逆序对是和上一个一样的,关键在于3和4的逆序对。3,4,1,2,0中3的逆序对为3个,顺序对为1个,由此可以得出:顺序对 + 逆序对 = 总数 - 1。移动位置之后:3的逆序对为0,而4的逆序对增加了一个,可以发现逆序数减少了2个(2 = 3 - 1)。所以此时序列的逆序数 = 上一个序列的逆序数 + (上一个序列的顺序对)- 上一个序列的逆序对。然后可以把顺序对 + 逆序对 = 总数 - 1带入进方程中。抽象出方程: sum += (n - 2 * a[i] - 1)。剩下的选取最小的逆序数就可以了。