# Meaning of problems
n integers different sequences processed by the ranking algorithm exchanging adjacent two sequence elements, in ascending order until the sequence is determined to be exchanged over many times quicksort
# Problem solution
method for sorting by exchanging only the adjacent values actually bubble sort, each set of adjacent values to find a reverse be exchanged during sorting, so that the entire sequence will reverse to the number of -1, the final after sorted, the number of reverse apparently 0, so the number of times for a minimum of switching is required bubble sort in reverse order of the sequence a
1 #include<bits/stdc++.h> 2 #define ll long long 3 using namespace std; 4 const int N=1e6+10; 5 int n; 6 int a[N]; 7 int ans[N]; 8 ll merge_sort(int l,int r){ 9 if(l>=r) return 0; 10 int mid=l+r>>1; 11 ll res=merge_sort(l,mid)+merge_sort(mid+1,r); 12 13 int k = 0,i = l,j = mid+1; 14 while(i <= mid && j <= r){ 15 if(a[i] <= a[j]) 16 ans[k++]=a[i++]; 17 else{ 18 ans[k++]=a[j++]; 19 res+=mid-i+1; 20 } 21 } 22 while(i <= mid) ans[k++] = a[i++]; 23 while(j <= r) ans[k++] = a[j++]; 24 25 for(int i = l,j = 0; i <= r; i++,j++) 26 a[i]=ans[j]; 27 return res; 28 } 29 int main(){ 30 ios::sync_with_stdio(0); 31 cin.tie(0); 32 cout.tie(0); 33 while(cin>>n&&n){ 34 for(int i=0;i<n;i++) 35 cin>>a[i]; 36 37 cout<<merge_sort(0,n-1)<<endl; 38 } 39 }