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
-----------AC----------------
虽然数据只有5000,但暴力会超时
注意一点:当第p[i]个数据跑到最后面时,总数应该先减去这个a[i]的逆序数,sum-num[i],然后这个a[i]排到最后面,即加上除了p[i]外比p[i]大的数目,n-num[i]-1,即总数sum=sum-num[i]+(n-num[i]-1)
模拟一下例题
1 2 3 4 5 6 7 8 9 10
p[i] 1 3 6 9 0 8 5 7 4 2
num[i] 1 2 4 6 0 4 2 2 1 0
sum=22
当p[1]排到后面,更新num[i],每个比p[1]大的都加一,sum=sum-num[i]+(n-num[i]-1)
1 2 3 4 5 6 7 8 9 10
p[i] 3 6 9 0 8 5 7 4 2 1
num[i] 3 5 7 0 5 3 3 2 1 0
sum=29
1 #include<iostream> 2 #include<cstring> 3 #include<cmath> 4 #include<cstdio> 5 #include<algorithm> 6 using namespace std; 7 #define MAXN 5010 8 #define INF 999999999 9 int main() 10 { 11 int n; 12 while(cin>>n) 13 { 14 int p[MAXN],sum = 0,num[MAXN]; 15 int i,j; 16 for(i = 0; i < n; ++i) 17 cin>>p[i]; 18 memset(num,0,sizeof(num)); 19 for(i = 0; i < n-1; ++i) 20 { 21 for(j = i; j < n; ++j) 22 if(p[i] > p[j]) 23 num[i]++; 24 sum += num[i]; 25 cout<<num[i]<<" "; 26 } 27 int t = sum; 28 for(i = 0; i< n-1; ++i) 29 { 30 t = t - num[i] + (n-num[i]-1); 31 sum = min(sum,t); 32 // cout<<t<<endl; 33 //更新num[i]值 34 for(j = i+1; j<n; ++j) 35 if(p[j] >p [i]) 36 num[j] ++; 37 } 38 cout<<sum<<endl; 39 } 40 return 0; 41 }