Problem:
Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

3 \leq N \leq 2 \times 10^3

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23

Solution in Rust (1.15.1) (judge verdict: Accepted)

use std::io::{self, BufRead, BufWriter, Write};

fn solve<R, W>(reader: R, mut writer: W)
where
    R: BufRead,
    W: Write,
{
    let mut lines = reader.lines();
    let _ = lines.next();
    let a_line = lines.next().unwrap().unwrap();
    let splited = a_line.trim().split_whitespace();
    let mut ls: Vec<i32> = splited.map(|s| s.parse().unwrap()).collect();
    ls.sort();

    let mut ans = 0;
    for i in 0..ls.len() {
        for j in i + 1..ls.len() {
            let k = bin_search(&ls[j + 1..], (ls[i] - ls[j]).abs(), ls[i] + ls[j]);
            ans += k;
        }
    }

    writeln!(&mut writer, "{}", ans).unwrap();
}

fn bin_search(ls: &[i32], n0: i32, n1: i32) -> i32 {
    let mut ans = 0;
    for i in 0..ls.len() {
        if ls[i] <= n0 {
            continue;
        }
        if n1 <= ls[i] {
            break;
        }
        ans += 1;
    }
    ans
}

fn main() {
    let stdio = io::stdin();
    let input = stdio.lock();

    let stdout = io::stdout();
    let output = BufWriter::new(stdout.lock());

    solve(input, output);
}

#[cfg(test)]
mod tests {
    use super::*;

    const TESTS: &'static [(&'static [u8], &'static [u8])] = &[
        (
            br"4
3 4 2 1",
            br"1
",
        ),
        (
            br"3
1 1000 1",
            br"0
",
        ),
        (
            br"7
218 786 704 233 645 728 389",
            br"23
",
        ),
    ];

    #[test]
    fn test_d() {
        for &(input, expected) in TESTS {
            let mut output = Vec::new();
            solve(input, &mut output);
            let expected_str = String::from_utf8(expected.to_vec()).unwrap();
            let output_str = String::from_utf8(output).unwrap();
            assert_eq!(expected_str, output_str);
        }
    }
}