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.
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 }