Reverse number of pairs (merge algorithm)

Title Description
Given a length n of the integer sequence number, please number of reverse calculation of the number of columns.

Reverse pairs defined as follows: for i-th and j-th element of the series, if the full i <j and a [i]> a [j], which is the reverse of a; otherwise not.

Input format
The first row contains an integer n, denotes the length of the sequence.

The second line contains n integer representing the entire number of columns.

Output format
output an integer representing the number of reverse order.

Data range
1≤n≤100000

Sample input:

6
2 3 4 5 6 1

Sample output:

5
算法思路:
1.利用归并算法,分区mid=l+r>>2
2.递归,left[l,mid] 和right[mid+1,r]
3,归并时采用双指针i=l;j=mid+1.如果有右边的元素小于左边的元素,产生的逆序对个数有mid=i+1;继续归并。
4.临时数组复制到原有数组中。
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N=100010;
 4 int q[N],tmp[N];
 5 typedef long long LL;
 6 
 7 LL merge_sort(int q[],int l,int r)
 8 {    
 9     if(l>=r)return 0;
10     int mid=l+r>>1;
11     LL res=merge_sort(q,l,mid)+merge_sort(q,mid+1, r); // represents the number of data would exceed the range of int.
12 is      int K = 0 , I = L, J = MID + . 1 ;
 13 is      the while (I <= MID && J <= R & lt)
 14          IF (Q [I] <= Q [J]) tmp [K ++] = Q [I ++ ];
 15          the else  
16          {    
 . 17              RES = MID + -i + . 1 ; // if the left half of the element is larger than the right number, the number behind each element is also larger than that on the left, a total mid-i + 1 th.
18 is              tmp [K ++] = Q [J ++ ];
 . 19              
20 is          }
 21 is      the while (I <= MID) tmp [K ++] = Q [I ++ ];
 22 is      the while (J <= R & lt) tmp [K ++] = Q [J ++ ];
 23      
24-     for(int i=l,j=0;i<=r;i++,j++) q[i]=tmp[j];
25     return res;
26 }
27 int main(){
28     int n;
29     scanf("%d",&n);
30     for(int i=0;i<n;i++)
31         scanf("%d",&q[i]);
32     cout<<merge_sort(q,0,n-1)<<endl; 
33     return 0;
34 }

 

 

Guess you like

Origin www.cnblogs.com/pythen/p/11770321.html