Problem:
Score : 700 points

Problem Statement

You are given N integers A_1, A_2, ..., A_N.

Consider the sums of all non-empty subsequences of A. There are 2^N - 1 such sums, an odd number.

Let the list of these sums in non-decreasing order be S_1, S_2, ..., S_{2^N - 1}.

Find the median of this list, S_{2^{N-1}}.

Constraints

1 \leq N \leq 2000

1 \leq A_i \leq 2000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the median of the sorted list of the sums of all non-empty subsequences of A.

Sample Input 1

3
1 2 1

Sample Output 1

2

In this case, S = (1, 1, 2, 2, 3, 3, 4). Its median is S_4 = 2.

Sample Input 2

1
58

Sample Output 2

58

In this case, S = (58).

Solution in Rust (1.15.1) (judge verdict: Runtime Error)

#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::str::*;
#[allow(unused_imports)]
use std::mem::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::usize;

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();
    line.trim().to_string().parse().ok().unwrap()
}

#[allow(dead_code)]
fn read_cols<T: FromStr>() -> Vec<T> {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();

    line.trim()
        .split_whitespace()
        .map(|s| s.parse().ok().unwrap())
        .collect()
}

/// Returns the minimum partial sum of nums,
/// greater than or equal to bound.
fn calc_partial_sum_lower_bound(
    nums: &[usize],
    bound: usize,
    sums: &[usize],
    cache: &mut Vec<Vec<Option<usize>>>,
) -> usize {
    if bound <= 0 {
        return 0;
    }

    let (last, remains) = match nums.split_last() {
        Some(pair) => pair,
        None => return usize::max_value(),
    };

    let cache_key = remains.len();

    if sums[cache_key] < bound {
        // total sum is less than bound
        return usize::max_value();
    }

    if let Some(r) = cache[cache_key][bound as usize] {
        return r;
    }

    let min_without_last = calc_partial_sum_lower_bound(remains, bound, sums, cache);
    let min_with_last = match calc_partial_sum_lower_bound(remains, bound - last, sums, cache) {
        n if n == usize::max_value() => usize::max_value(),
        n => n + last,
    };

    let ret = min(min_without_last, min_with_last);
    cache[cache_key][bound as usize] = Some(ret);
    ret
}

/// Returns the minimum partial sum of nums,
/// greater than or equal to bound.
fn calc_iterative(nums: &[usize], bound: usize, sums: &[usize]) -> usize {
    if bound <= 0 {
        return 0;
    }

    let mut dp = Vec::new();
    dp.resize(nums.len(), Vec::<usize>::new());

    dp[0].resize(nums[0] + 1, nums[0]);

    for (i, &num) in nums.iter().skip(1).enumerate() {
        dp[i].resize(sums[i] + 1, usize::max_value());
        for j in 0..min(sums[i], bound) + 1 {
            let without_i = if j < dp[i - 1].len() {
                dp[i - 1][j]
            } else {
                usize::max_value()
            };

            let with_i = if j < nums[i] {
                nums[i]
            } else if j - num < dp[i - 1].len() {
                dp[i - 1][j - num] + num
            } else {
                usize::max_value()
            };

            dp[i][j] = min(without_i, with_i);
        }
    }

    dp[nums.len()][bound]
}

fn main() {
    let n = read::<usize>();
    let nums = {
        let mut nums = read_cols::<usize>();
        nums.sort();
        nums
    };
    assert_eq!(n, nums.len());

    // Idea:
    //  When S=a_1+...+a_n and S_i (i=1, ...) is i-th partial sum
    //  in ascending order and S_0 = 0,
    //  S_{2^n-1-i} = S - S_i,
    //  and if S_i <= S/2, then S_{2^n-1-i} >= S/2.
    //  By this fact, minimum S_k where satisfies S_k >= S/2
    //  is the median of partial sums.
    let sums = nums.iter()
        .scan(0, |sum, &num| {
            *sum += num;
            Some(*sum)
        })
        .collect::<Vec<_>>();

    let mut cache = Vec::new();
    cache.resize(n, Vec::<Option<usize>>::new());
    for (i, c) in cache.iter_mut().enumerate() {
        c.resize(sums[i] + 1, None);
    }

    let total_sum = sums.last().unwrap();
    let answer = calc_partial_sum_lower_bound(&nums, (total_sum + 1) / 2, &sums, &mut cache);

    println!("{}", answer);
}