Merge sort applications - seeking to reverse the number of

topic:

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 column number, if satisfied 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

1n1000001≤n≤100000

Sample input:

6
2 3 4 5 6 1

Sample output:

5

Code:

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 const int N = 1e7;
 6 
 7 long arr[N];
 8 long help[N];
 9 int n;
10 
11 long long ans;
12 
13 void union_sort(int l, int r){
14     if(l >= r)return;
15     int mid = l + r >> 1;
16     union_sort(l, mid);
17     union_sort(mid+1,r);
18     int i = l, j = mid + 1, k = 1;
19     while(i <= mid && j <= r){
20         if(arr[i] <= arr[j])
21             help[k++] = arr[i++];
22         else{
23             help[k++] = arr[j++];
24             ans += mid - i + 1;
25         }
26     }
27     while(i <= mid)help[k++] = arr[i++];
28     while(j <= r)help[k++] = arr[j++];
29     for(int i = l, j = 1;i <= r;++i)
30         arr[i] = help[j++];
31 }
32 
33 int main(){
34     cin >> n;
35     for(int i = 1;i <= n;++i)cin >> arr[i];
36     union_sort(1, n);
37     cout << ans;
38     return 0;
39 }
View Code

 

Guess you like

Origin www.cnblogs.com/sxq-study/p/12378693.html