Problem:
Score : 600 points

Problem Statement

The squirrel Chokudai has N acorns.
One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.

His plan is as follows:

Get out of the nest with N acorns in his hands.

Go to Exchange A and do some trades.

Go to Exchange B and do some trades.

Go to Exchange A and do some trades.

Go back to the nest.

In Exchange X (X = A, B), he can perform the following operations any integer number of times (possibly zero) in any order:

Lose g_{X} acorns and gain 1 gram of gold.

Gain g_{X} acorns and lose 1 gram of gold.

Lose s_{X} acorns and gain 1 gram of silver.

Gain s_{X} acorns and lose 1 gram of silver.

Lose b_{X} acorns and gain 1 gram of bronze.

Gain b_{X} acorns and lose 1 gram of bronze.

Naturally, he cannot perform an operation that would leave him with a negative amount of acorns, gold, silver, or bronze.

What is the maximum number of acorns that he can bring to the nest?
Note that gold, silver, or bronze brought to the nest would be worthless because he is just a squirrel.

Constraints

1 \leq N \leq 5000

1 \leq g_{X} \leq 5000

1 \leq s_{X} \leq 5000

1 \leq b_{X} \leq 5000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
g_A s_A b_A
g_B s_B b_B

Output

Print the maximum number of acorns that Chokudai can bring to the nest.

Sample Input 1

23
1 1 1
2 1 1

Sample Output 1

46

He can bring 46 acorns to the nest, as follows:

In Exchange A, trade 23 acorns for 23 grams of gold. {acorns, gold, silver, bronze}={ 0,23,0,0 }

In Exchange B, trade 23 grams of gold for 46 acorns. {acorns, gold, silver, bronze}={ 46,0,0,0 }

In Exchange A, trade nothing. {acorns, gold, silver, bronze}={ 46,0,0,0 }

He cannot have 47 or more acorns, so the answer is 46.

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

#[derive(PartialEq, PartialOrd, Copy, Clone)]
pub struct Total<T>(pub T);

impl<T: PartialEq> Eq for Total<T> {}

impl<T: PartialOrd> Ord for Total<T> {
    fn cmp(&self, other: &Total<T>) -> std::cmp::Ordering {
        self.0.partial_cmp(&other.0).unwrap()
    }
}

fn argsort<T: std::cmp::Ord + std::marker::Copy>(v: &Vec<T>) -> Vec<usize> {
    let mut sort_v = Vec::new();
    for i in 0..v.len() {
        sort_v.push((v[i], i));
    }
    sort_v.sort();
    sort_v.iter().map(|x| x.1).collect::<Vec<usize>>()
}

fn main() {
    let mut n = read::<i64>();
    let v = read_vec::<i64>();
    let (ga, sa, ba) = (v[0], v[1], v[2]);
    let v = read_vec::<i64>();
    let (gb, sb, bb) = (v[0], v[1], v[2]);
    let mut ans = 0;
    for gi in 0..n + 1 {
        if gi * ga > n {
            break;
        }
        for si in 0..n + 1 {
            if gi * ga + si * sa > n {
                break;
            }
            let mut residual = n - (gi * ga + si * sa);
            if bb > ba {
                residual = (residual / ba) * bb + (residual - (residual / ba) * ba);
            }
            ans = max(ans, gb * gi + sb * si + residual);
        }
    }

    n = ans;

    let order = argsort(&vec![ga / gb, sa / sb, ba / bb]);
    let rates = vec![(gb, ga), (sb, sa), (bb, ba)];

    if rates[order[2]].0 >= rates[order[2]].1 {
        println!("{:?}", n);
        return;
    }
    let (gb, ga) = rates[order[2]];
    let (sb, sa) = rates[order[1]];
    let (bb, ba) = rates[order[0]];

    let max_enable = (n / gb) as i64;
    let min_enable = max(0, max_enable as i64 - 25001);

    let mut ans = n;
    for gi in min_enable..max_enable + 1 {
        for si in 0..n {
            if gi * gb + si * sb > n {
                break;
            }
            let mut residual = n - (gi * gb + si * sb);
            if ba > bb {
                residual = (residual / bb) * ba + (residual - (residual / bb) * bb);
            }
            ans = max(ans, residual + gi * ga + si * sa);
        }
    }
    println!("{:?}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}