#[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::{HashMap, HashSet}; mod util { use std::io::stdin; use std::str::FromStr; use std::fmt::Debug; #[allow(dead_code)] pub fn line() -> String { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.trim().to_string() } #[allow(dead_code)] pub fn get() -> T where ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.trim().parse().unwrap() } #[allow(dead_code)] pub fn gets() -> Vec where ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|t| t.parse().unwrap()) .collect() } #[allow(dead_code)] pub fn get2() -> (T, U) where ::Err: Debug, ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), ) } #[allow(dead_code)] pub fn get3() -> (S, T, U) where ::Err: Debug, ::Err: Debug, ::Err: Debug, { let mut line: String = String::new(); stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), ) } } #[allow(unused_macros)] macro_rules! debug { ($x: expr) => { println!("{}: {:?}", stringify!($x), $x) } } fn main() { let n: usize = util::get(); let ab: Vec<(i64, i64)> = (0..n).map(|_| util::get2()).collect(); let b_sum = ab.iter().map(|t| t.1).sum::(); let c: Vec<_> = ab.iter().map(|t| t.0 + t.1).collect(); let l = &c[..n / 2]; let r = &c[n / 2..]; let mut l_comb = Vec::new(); let mut r_comb = Vec::new(); for i in 0..1 << l.len() { let mut sum = 0; for j in 0..l.len() { if i >> j & 1 == 1 { sum += l[j]; } } l_comb.push(sum); } for i in 0..1 << r.len() { let mut sum = 0; for j in 0..r.len() { if i >> j & 1 == 1 { sum += r[j]; } } r_comb.push(sum); } l_comb.sort(); l_comb.dedup(); r_comb.sort(); r_comb.dedup(); let mut ans = i64::max_value(); for &x in &l_comb { if x > b_sum { ans = min(ans, x - b_sum); } else { let rest = b_sum - x; match r_comb.binary_search(&rest) { Ok(_) => { ans = 0; break; } Err(i) => { if i >= r_comb.len() { if r_comb.len() > 0 { ans = min(ans, b_sum - x - r_comb[r_comb.len() - 1]) } } else { ans = min(ans, r_comb[i] + x - b_sum); if i > 0 { ans = min(ans, b_sum - r_comb[i - 1] - x); } } } } } } println!("{}", ans); }