Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6937 Accepted Submission(s): 4233
Problem 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
Author
CHEN, Gaoli
Source
Recommend
Ignatius.L
题意:将一个n个元素的排列,可以将第一个元素放到最后一个元素后面得出n个排列,求这n个排列的最少逆序数对
题解:用树状数组,按顺序插入,求出排列的逆序数对temp,模拟将第一个元素移走,那么逆序数对就减少sum(a-1)个,将这个数放到最后一位,逆序数对就增加(n-1)-sum(a-1)对,所以每次转变就有temp=temp+n-1-2*sum(a【i】-1),依次可以算出最少的逆序数对值
#include<stdio.h> #include<string.h> #define MAX 1000005 int tree[MAX],a[5005]; int low_bit(int x) { return x&(-x); } void add(int x,int y) { while(x<MAX) { tree[x]+=y; x+=low_bit(x); } } int ques(int x) { int temp=0; while(x>0) { temp+=tree[x]; x-=low_bit(x); } return temp; } int main() { int temp,sum,n,i; while(scanf("%d",&n)>0) { memset(tree,0,sizeof(tree)); for(i=1;i<=n;i++) scanf("%d",a+i); for(temp=0,i=n;i>=1;i--) { a[i]++; temp=temp+ques(a[i]-1); add(a[i],1); } sum=temp; for(i=1;i<n;i++) { temp=temp+n-1-2*ques(a[i]-1); if(temp<sum) sum=temp; } printf("%d\n",sum); } return 0; }