Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

The Number of Inversions

For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap(A[j], A[j-1])
cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2

Solution in JAVA (judge verdict: Accepted)

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
class Main {
	public static void main(String args[]) {
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		List<Integer> array = new ArrayList<Integer>();
		
		for(int i = 0; i < num; i ++ ){
			array.add(scanner.nextInt());
		}
		
		

        System.out.println( count(array, 0, num) );
        
        scanner.close();
	}

	public static long merge(List<Integer> array, int left, int middle, int right) { 
		long count = 0;
		int sub_left,sub_right;
		int max = 1000000000;
		int i,j,k;
		
		//ソート処理
		sub_left = middle - left;
		sub_right = right - middle;
		List<Integer> array_left = new ArrayList<Integer>(sub_left + 1);
		List<Integer> array_right = new ArrayList<Integer>(sub_right + 1);
		
		for(i = 0;i < sub_left;i ++){
			array_left.add( array.get(left + i) );
		}
		
		for(i = 0;i < sub_right;i ++){
			array_right.add( array.get(middle + i) );
		}
		
		array_left.add(max);
		array_right.add( max);
		
		i = 0; j = 0;
		for(k = left;k < right;k ++){
			if(array_left.get(i) < array_right.get(j)) {
				//i ++;
				array.set(k, array_left.get(i ++));
			}else{
				//j ++;
				array.set(k, array_right.get(j ++));
				count += (sub_left - i);
			}
		}
		return count;
	}

	public static long count(List<Integer> array, int left, int right) { 
		int middle;
		if(left + 1 >= right){
			if(left < right)return 0;
			return 1;
		}else{
			middle = (left + right) / 2;
			return (count(array, left, middle) + count(array, middle, right) +
					merge(array, left, middle, right));
		}
	}
}