1 #include<iostream> 2 #include<stdio.h> 3 #define MAXN 500000 4 using namespace std; 5 6 int a[MAXN]; 7 int c[MAXN]; 8 long long n; 9 void Merge(int le, int mid, int rh); 10 void MergeSort(int le, int rh); 11 int main() 12 { 13 //freopen("acm.acm","r",stdin); 14 int num; 15 int i; 16 while(cin>>num && num) 17 { 18 n = 0; 19 for(i = 0; i < num; ++ i) 20 cin>>a[i]; 21 MergeSort(0,num-1); 22 //for(i = 0; i < num; ++ i) 23 // cout<<a[i]<<" "; 24 //cout<<endl; 25 cout<<n<<endl; 26 } 27 } 28 29 void MergeSort(int le, int rh){ 30 31 32 if (rh>le) 33 { 34 int mid = (le+rh) >> 1; 35 MergeSort(le,mid); 36 MergeSort(mid + 1,rh); 37 Merge(le, mid, rh); 38 } 39 } 40 41 void Merge(int le, int mid, int rh) 42 { 43 int i, j,p = 1; 44 for (i = le, j = mid+1; i <= mid && j <= rh; ) 45 { 46 if (a[j] < a[i]) 47 { 48 c[p++] = a[j++]; 49 n += mid - i + 1; 50 } 51 else c[p++] = a[i++]; 52 } 53 while ( j <= rh ) 54 c[p++] = a[j++]; 55 while( i <= mid ) 56 c[p++] = a[i++]; 57 58 for (i = le; i <= rh; ++i) 59 { 60 a[i] = c[i - le + 1]; 61 } 62 }
时间: 2024-10-25 16:18:14