use std::collections::HashMap; fn main() { let input = Input::read(); let mut memo = HashMap::new(); let ans = rec(&input, 0, 0, 0, 0, &mut memo); println!("{}", ans); } fn rec( input: &Input, used_products: usize, used_magics: usize, w: i64, v: i64, memo: &mut HashMap<(usize, usize, i64, i64), i64>, ) -> i64 { if w < 0 || w > input.weight_limit { return 0; } if let Some(&sum_v) = memo.get(&(used_products, used_magics, w, v)) { return sum_v; } let mut max_value = v; for product in 0..input.product_num { if (used_products >> product) & 1 == 1 { continue; } let next_used_products = used_products | (1 << product); let value1 = rec(input, next_used_products, used_magics, w, v, memo); let value2 = rec( input, next_used_products, used_magics, w + input.weights[product], v + input.values[product], memo, ); max_value = max_value.max(value1).max(value2); } for magic in 0..input.magic_num { if (used_magics >> magic) & 1 == 1 { continue; } let next_used_magics = used_magics | (1 << magic); let value1 = rec(input, used_products, next_used_magics, w, v, memo); let value2 = rec( input, used_products, next_used_magics, w - input.reduce_weight[magic], v - input.reduce_value[magic], memo, ); max_value = max_value.max(value1).max(value2); } memo.insert((used_products, used_magics, w, v), max_value); max_value } struct Input { product_num: usize, magic_num: usize, weights: Vec, values: Vec, weight_limit: i64, reduce_weight: Vec, reduce_value: Vec, } impl Input { fn read() -> Self { let (product_num, magic_num, weight_limit) = { let mut line = String::new(); std::io::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(), ) }; let weights: Vec<_> = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|x| x.parse::().unwrap()) .collect() }; let values: Vec<_> = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|x| x.parse::().unwrap()) .collect() }; let reduce_weight: Vec<_> = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|x| x.parse::().unwrap()) .collect() }; let reduce_value: Vec<_> = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|x| x.parse::().unwrap()) .collect() }; Self { product_num, magic_num, weights, values, weight_limit, reduce_weight, reduce_value, } } }