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 Rust (judge verdict: Accepted)

use std::io::*;
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::cmp::{min, max};

struct Scanner<R: Read> {
    reader: R,
    buffer: String,
}

#[allow(dead_code)]
impl<R: Read> Scanner<R> {
    fn new(reader: R) -> Scanner<R> {
        Scanner { reader: reader, buffer: String::new() }
    }

    // fn line(&mut self) -> String {
    //     self.buffer = self.reader.by_ref().bytes().map(|c| c.unwrap() as char)
    //         .skip_while(|&c| c == '\n' || c == '\r')
    //         .take_while(|&c| !(c == '\n' || c == '\r'))
    //         .collect::<String>();
    //     self.buffer.clone()
    // }

    fn read_buffer(&mut self) {
        self.buffer = self.reader.by_ref().bytes().map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
    }

    fn safe_read<T: FromStr>(&mut self) -> Option<T> {
        self.read_buffer();
        if self.buffer.is_empty() {
            None
        } else {
            self.buffer.parse::<T>().ok()
        }
    }

    fn read<T: FromStr>(&mut self) -> T {
        if let Some(s) = self.safe_read() {
            s
        } else {
            // writeln!(std::io::stderr(), "Terminated with EOF").unwrap();
            std::process::exit(0);
        }
    }

    fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
        (0..len).map(|_| self.read()).collect()
    }

    fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> {
        (0..row).map(|_| self.vec(col)).collect()
    }
}

trait Joinable {
    fn join(self, sep: &str) -> String;
}

impl<U: ToString, T: Iterator<Item=U>> Joinable for T {
    fn join(self, sep: &str) -> String {
        self.map(|x| x.to_string()).collect::<Vec<_>>().join(sep)
    }
}

fn main() {
    std::thread::Builder::new()
        .stack_size(104_857_600)
        .spawn(solve)
        .unwrap()
        .join()
        .unwrap();
}

pub trait Monoid {
    type T: Clone;
    fn id() -> Self::T;
    fn op(a: &Self::T, b: &Self::T) -> Self::T;
}

pub trait Inv {
    fn inv(a: &Self) -> Self;
}

#[derive(PartialEq, Eq, Clone, Hash, Debug, Default)]
struct FenwichTree<M: Monoid> {
    pub ary: Vec<M::T>,
    pub dat: Vec<M::T>,
    pub size: usize,
}

#[allow(dead_code)]
impl<M: Monoid> FenwichTree<M> {
    pub fn new(n: usize) -> FenwichTree<M> {
        FenwichTree {
            ary: vec![M::id(); n],
            dat: vec![M::id(); n + 1],
            size: n,
        }
    }

    pub fn add(&mut self, k: usize, x: &M::T) {
        assert!(k <= self.size);
        self.ary[k] = M::op(&self.ary[k], &x);
        let mut k = k + 1;
        while k <= self.size {
            self.dat[k] = M::op(&self.dat[k], &x);
            k += k & k.wrapping_neg();
        }
    }

    pub fn accumulate(&self, k: usize) -> M::T {
        assert!(k <= self.size);
        let mut k = k;
        let mut acc = M::id();
        while k > 0 {
            acc = M::op(&acc, &self.dat[k]);
            k &= k - 1;
        }
        acc
    }

    pub fn get(&self, k: usize) -> M::T {
        assert!(k <= self.size);
        self.ary[k].clone()
    }
}

#[allow(dead_code)]
impl<M> FenwichTree<M> where M: Monoid, <M as Monoid>::T: Inv {
    pub fn set(&mut self, k: usize, x: &M::T) {
        assert!(k <= self.size);
        let y = self.get(k);
        self.add(k, &M::op(&Inv::inv(&y), x));
    }

    pub fn range_accumulate(&self, l: usize, r: usize) -> M::T {
        assert!(l <= r);
        assert!(r <= self.size);
        let al = self.accumulate(l);
        let ar = self.accumulate(r);
        M::op(&al, &Inv::inv(&ar))
    }
}

use std::iter::FromIterator;
#[allow(dead_code)]
impl<M> FromIterator<M::T> for FenwichTree<M> where M: Monoid {
    fn from_iter<I: IntoIterator<Item = M::T>>(iter: I) -> Self {
        let dat = iter.into_iter().collect::<Vec<M::T>>();
        let size = dat.len();
        let mut res = FenwichTree::new(size);
        for (i, x) in dat.iter().enumerate() {
            res.add(i, x);
        }
        res
    }
}

#[allow(dead_code)]
struct IntAddMonoid;
impl Monoid for IntAddMonoid {
    type T = i32;
    fn id() -> Self::T {
        0
    }
    fn op(a: &Self::T, b: &Self::T) -> Self::T {
        a + b
    }
}
impl Inv for i32 {
    fn inv(a: &Self) -> Self {
        -a
    }
}

type IntAddFenwichTree = FenwichTree<IntAddMonoid>;

fn count_swap(a: &[i32]) -> usize {
    let n = a.len();
    let mut map: BTreeMap<i32, usize> = a.iter().map(|&x| (x, 0)).collect();
    for (i, (_, id)) in map.iter_mut().enumerate() {
        *id = i;
    }
    let mut ft = IntAddFenwichTree::new(n);
    let mut res = 0;
    for x in a.iter().rev() {
        let x = map[&x];
        res += ft.accumulate(x) as usize;
        ft.add(x, &1);
    }
    res
}

fn solve() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);

    loop {
        let n: usize = sc.read();
        let a = sc.vec(n);
        println!("{}", count_swap(&a[..]));
    }
}