Problem:
Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

The input is given from Standard Input in the following format:

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

3 1 1
1 2 1
2 1 2
3 3 10

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.

Solution in Rust (1.15.1) (judge verdict: Memory Limit Exceeded)

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}
 
#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};
 
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}
 
#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };
 
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
 
    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };
 
    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };
 
    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };
 
    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}
 
use std::cmp::Ordering;
 
/// Equivalent to std::lowerbound and std::upperbound in c++
pub trait BinarySearch<T> {
    fn lower_bound(&self, &T) -> usize;
    fn upper_bound(&self, &T) -> usize;
}
 
impl<T: Ord> BinarySearch<T> for [T] {
    fn lower_bound(&self, x: &T) -> usize {
        let mut low = 0;
        let mut high = self.len();
 
        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(x) {
                Ordering::Less => {
                    low = mid + 1;
                }
                Ordering::Equal | Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
 
    fn upper_bound(&self, x: &T) -> usize {
        let mut low = 0;
        let mut high = self.len();
 
        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(x) {
                Ordering::Less | Ordering::Equal => {
                    low = mid + 1;
                }
                Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
}
 
 
 
 
 
 
use std::cmp;
use std::cmp::min;
use std::collections::BTreeMap;
use std::process;
use std::cmp::Ord;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::collections::BTreeSet;
use std::mem;
 
#[derive(PartialEq, Eq)]
pub struct point(i64, i64, i64);
impl Ord for point {
    fn cmp(&self, other: &point) -> Ordering {
        self.0.cmp(&other.0)
    }
}
 
impl PartialOrd for point {
    fn partial_cmp(&self, other: &point) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
/*
impl PartialEq for point {
    fn eq(&self, other: &point) -> bool {
        self.0 == other.0
    }
}
impl Eq for point {
    fn eq(&self, other: &point) -> bool {
        self.0 == other.0
    }s
}*/
type P = (i64 , i64);
fn bfs(start:&P, goal:&P, map:&Vec<Vec<char>>) -> i64 {
        let dx = vec![1, 0, -1, 0];
        let dy = vec![0, 1, 0, -1];
        let s = (start.0, start.1);
        let g = (goal.0 , goal.1);
        let mut queue:VecDeque<P> = VecDeque::new();
        let mut d:Vec<Vec<i64>> = Vec::new();
        for i in 0..map.len(){
            d.push(Vec::new());
            for j in 0..map[i].len(){
                d[i].push(30000000);
            }
        }
        queue.push_back((s.0, s.1));
        d[s.0 as usize][s.1 as usize] = 0;
        while(queue.len()!=0){
            let mut p:P = queue[0];
            queue.pop_front();
            if p.0 == g.0 && p.1 == g.1{break;}
            for i in 0..4{
                let nx = p.0 + dx[i];
                let ny = p.1 + dy[i];
                if (0<=nx && nx <map.len() as i64 && 0<=ny &&ny<map[0].len() as i64 && map[nx as usize][ny as usize]!='#' && d[nx as usize][ny as usize] == 30000000 ){
                    queue.push_back((nx, ny));
                    d[nx as usize][ny as usize] = d[p.0 as usize][p.1 as usize] + 1;
                }
            }
 
        }
        d[goal.0 as usize][goal.1 as usize]
}
 
fn bfs01(start:&P, goal:&P, map:&Vec<Vec<char>>) -> i64 {
        let dx = vec![1, 0, -1, 0];
        let dy = vec![0, 1, 0, -1];
        let s = (start.0, start.1);
        let g = (goal.0 , goal.1);
        let mut queue:VecDeque<P> = VecDeque::new();
        let mut d:Vec<Vec<i64>> = Vec::new();
        for i in 0..map.len(){
            d.push(Vec::new());
            for j in 0..map[i].len(){
                d[i].push(30000000);
            }
        }
        queue.push_back((s.0, s.1));
        d[s.0 as usize][s.1 as usize] = 0;
        while(queue.len()!=0){
            let mut p:P = queue[0];
            queue.pop_front();
            if p.0 == g.0 && p.1 == g.1{break;}
            for i in 0..4{
                let nx = p.0 + dx[i];
                let ny = p.1 + dy[i];
                if (0<=nx && nx <map.len() as i64 && 0<=ny &&ny<map[0].len() as i64 && d[nx as usize][ny as usize] == 30000000 ){
                    if map[nx as usize][ny as usize] == '#'{
                        queue.push_back((nx, ny));
                        d[nx as usize][ny as usize] = d[p.0 as usize][p.1 as usize] + 1;
                    }
                    else{
                        queue.push_front((nx, ny));
                        d[nx as usize][ny as usize] = d[p.0 as usize][p.1 as usize];
                    }
                }
            }
 
        }
        d[goal.0 as usize][goal.1 as usize]
}
struct UnionFind_W{
    par:Vec<usize>,
    rank:Vec<usize>,
    size:Vec<usize>,
    diff_weight:Vec<i64>,    
}
impl UnionFind_W{
    fn init(n:usize) -> UnionFind_W{
        let mut par = vec![0;n];
        for i in 0..n{
            par[i] = i;    
        }
        UnionFind_W{
            par:par,
            rank:vec![0;n], 
            size:vec![1;n], 
            diff_weight:vec![0i64;n],
        }
    }
    fn find(&mut self, x:usize) ->usize{
        if(self.par[x] == x){
            x    
        }
        else{
            let p = self.par[x];
            let r = self.find(p);
            self.diff_weight[x] += self.diff_weight[p];
            self.par[x] = r;
            r
        }
    }
    fn weight(&mut self,x:usize)->i64{
        self.find(x);
        self.diff_weight[x]
    }
    fn diff(&mut self, x:usize, y:usize)->i64{
        let res = self.weight(x) - self.weight(y);
        res
    }
    fn same(&mut self, a:usize, b:usize)->bool{
        self.find(a) == self.find(b)    
    }
    fn unite(&mut self, xx:usize, yy:usize, ww:i64) -> bool{
        let mut w = ww.clone();
        let mut x = xx.clone();
        let mut y = yy.clone();

        w += self.weight(x);
        w -= self.weight(y);
        x = self.find(x);
        y = self.find(y);
        if (x == y) {return false;}
        if self.rank[x] < self.rank[y]{
            mem::swap(&mut x, &mut y);
            w = -w;
        }

        if self.rank[x] == self.rank[y]{
            self.rank[y] += 1;
        }
        self.par[y] = x;
        self.size[x] += self.size[y];
        self.diff_weight[y] = w;
        return true;
    }
    fn check_size(&mut self, a:usize) -> usize{
        let x = self.find(a);
        let s = self.size[x];
        s    
    }
}





struct UnionFind{
    par:Vec<usize>,
    rank:Vec<usize>,
    size:Vec<usize>,    
}
impl UnionFind{
    fn init(n:usize) -> UnionFind{
        let mut par = vec![0;n];
        for i in 0..n{
            par[i] = i;    
        }
        UnionFind{
            par:par,
            rank:vec![0;n], 
            size:vec![1;n], 
        }
    }
    fn find(&mut self, x:usize) ->usize{
        if(self.par[x] == x){
            x    
        }
        else{
            let p = self.par[x];
            let res = self.find(p);
            self.par[x] = res;
            res
        }
    }
    fn same(&mut self, a:usize, b:usize)->bool{
        self.find(a) == self.find(b)    
    }
    fn unite(&mut self, a:usize, b:usize){
        let x = self.find(a);
        let y = self.find(b);
        if x != y{
            if (self.rank[x] < self.rank[y]){
                self.par[x] = y;
                self.size[y] += self.size[x];
            }
            else{
                self.par[y] = x;
                self.size[x] += self.size[y];
                if(self.rank[x] == self.rank[y]){ self.rank[x]+=1;}
            }
        }
    }
    fn check_size(&mut self, a:usize) -> usize{
        let x = self.find(a);
        let s = self.size[x];
        s    
    }
}
fn gcd(a:usize, b:usize)->usize{
    if b==0{return a;}
    gcd(b, a%b)
}
fn lcm(a: usize, b: usize) -> usize {
    a / gcd(a, b) * b
}
fn extgcd(a:usize, b:usize, x:&mut usize, y:&mut usize)->usize{
    let mut d = a;
    if b != 0{
        d = extgcd(b, a%b, y, x);
        *y -= (a/b) * (*x);    
    }    
    else{
        *x = 1;
        *y = 0;
    }
    d
}

use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::any::{Any, TypeId};

struct vec2<T>(Vec<T>);
 
impl<T> Deref for vec2<T> {
    type Target = Vec<T>;
    fn deref(&self) -> &Vec<T> {
        &self.0
    }
}
 
impl<T> DerefMut for vec2<T> {
    fn deref_mut(&mut self) -> &mut Vec<T> {
        &mut self.0
    }
}
impl<T> Index<i64> for vec2<T> {
    type Output = T;
    fn index(&self, index: i64) -> &T {
        &self.0[index as usize]
    }
}
 
impl<T> IndexMut<i64> for vec2<T> {
    fn index_mut(&mut self, index: i64) -> &mut T {
        &mut self.0[index as usize]
    }
}

fn segment_sieve(a:usize, b:usize) -> Vec<bool>{
    let mut is_prime= vec![false; b+1];
    let mut is_prime_small= vec![false; b+1];
    for i in 0..b{
        if i*i>=b{break;}    
        is_prime_small[i] = true;
    }
    for i in 0..b{
        if i>=b-a{break;}
        is_prime[i] = true;    
    }
    for i in 2..b{
        if i*i>=b{break;}
        if is_prime_small[i] == true{


            let mut j = 2*i;
            while(j*j<b){
                is_prime_small[j] = false;
                j+=i;
            }
            
            j = cmp::max(2, ((a+i-1)/i)*i);
            while(j<b){
                is_prime[j-a] = false;
                j+=i;    
            }    
        }    
    }
    is_prime


}
fn sieve(n:usize) -> (Vec<bool>, Vec<usize>){
    let mut p:usize = 0;
    let mut is_prime = vec![false; n+1];
    let mut prime = Vec::new();
    for i in 0..n+1{
        is_prime[i] = true;
    }
    is_prime[0] = false;
    is_prime[1] = false;
    for i in 2..n+1{
        if is_prime[i]{
            prime.push(i as usize);
            let mut j = 2*i;
            while(j<=n){
                is_prime[j] = false;
                j+=i;
            }
        }
    }
    (is_prime, prime)
    
}
fn divisor(n:usize) -> Vec<usize>{
    let mut res:Vec<usize> = Vec::new(); 
    for i in 1..n+1{
        if i*i>n{break;}
        if n%i == 0{
            res.push(i);
            if i != n/i{
                res.push(n/i);    
            }    
        }    
    }
    res
}

fn prime_factor(nn:usize) -> HashMap<usize, usize>{
    let mut res:HashMap<usize, usize> = HashMap::new();
    let mut n = nn.clone();
    for i in 2..n+1{
        if i*i>n{break;}
        while(n%i == 0){
            *res.entry(i).or_insert(0) += 1;
            n/=i;    
        }    
    }
    if (n != 1){res.insert(n,1);}
    res
}

use std::collections::BinaryHeap;

#[derive(PartialEq)]
struct mf(i64);

impl Eq for mf {}

impl PartialOrd for mf {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}

impl Ord for mf {
    fn cmp(&self, other: &mf) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}




#[derive(Copy, Clone, Eq, PartialEq)]
struct edge1{from:usize, to:usize, cost:i64}
impl Ord for edge1 {
    fn cmp(&self, other: &edge1) -> Ordering {
        other.cost.cmp(&self.cost)
    }
}

impl PartialOrd for edge1 {
    fn partial_cmp(&self, other: &edge1) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
fn kruskal(es:&mut Vec<edge1>, n:usize) -> i64{
    es.sort();
    es.reverse();
    let mut uf =  UnionFind::init(n);
    let mut res = 0;
    for i in 0..es.len(){
        let e = es[i];
        if uf.same(e.from, e.to) == false{
            uf.unite(e.from, e.to);
            res += e.cost;
        }

    }
    res
}




fn bellman_ford(s:usize, n:usize, inf:i64, es:&Vec<edge1>) -> Vec<i64>{
    let mut d = vec![inf;n];
    d[s] = 0;
    for j in 0..n-1{
        let mut update = false;
        for i in 0..es.len(){
            let e = es[i];
            if (d[e.from] != inf && d[e.to] > d[e.from] + e.cost){
                d[e.to] = d[e.from] + e.cost;
            }
                
        }
    }

    d
}
fn find_negative_loop(n:usize, es:&Vec<edge1>, inf:i64) -> bool{
    let mut d = vec![0;n];
    for i in 0..n{
        for j in 0..es.len(){
            let e = es[j];
            if d[e.to] > d[e.from] + e.cost{
                d[e.to] = d[e.from] + e.cost;
                if (i == n-1) {return false;}
            }
        }
    }
    return true;
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct State{
    cost: i64,
    position: usize,
}
impl Ord for State {
    fn cmp(&self, other: &State) -> Ordering {
        // Notice that the we flip the ordering on costs.
        // In case of a tie we compare positions - this step is necessary
        // to make implementations of `PartialEq` and `Ord` consistent.
        other.cost.cmp(&self.cost)
    }
}

// `PartialOrd` needs to be implemented as well.
impl PartialOrd for State {
    fn partial_cmp(&self, other: &State) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

struct edge2{
    to:usize,
    cost:i64,
}
fn dijkstra(adj_list: &Vec<Vec<edge2>>, start:usize, inf:i64) -> Vec<i64>{
    let mut d= vec![inf;adj_list.len()];
    let mut heap = BinaryHeap::new();
    d[start] = 0;
    heap.push(State{cost: 0, position: start });
    while (heap.len() != 0){
        let p = heap.pop().unwrap();
        let v = p.position;
        if(d[v] < p.cost) {continue;}
        for i in 0..adj_list[v].len(){
            let e = &adj_list[v][i];
            if d[e.to] > d[v] + e.cost{
                d[e.to] = d[v] + e.cost;
                heap.push(State{cost:d[e.to], position:e.to});
            }
        }
            
    }
    d
        
}
// no verify
fn prim(n:usize, cost:&Vec<Vec<i64>>, inf:i64, s:usize) -> i64{
    let mut mincost = vec![inf;n];
    let mut used = vec![false;n];
    mincost[s] = 0;
    let mut res = 0;
    while(true){
        let mut v:i64 = -1;
        for  u in 0..n{
            if (used[u] == false && (v == -1 || mincost[u] <mincost[v as usize])){v = u.clone() as i64;}
        }
        if v == -1{break;}
        used[v as usize] = true;
        res += mincost[v as usize];
        for u in 0.. n{
            mincost[u] = cmp::min(mincost[u], cost[v as usize][u]);
        }
    }
    return res;
}
//
fn find_negative_loop2(n:usize, es:&Vec<edge1>, inf:i64, dist:&mut Vec<i64>) -> Vec<bool>{
    let mut neg = vec![false;n];
    for i in 0..n{
        for j in 0..es.len(){
            
            let e = es[j];
            if dist[e.from] == inf{continue;}

            if dist[e.to] > dist[e.from] + e.cost{
                dist[e.to] = dist[e.from] + e.cost;
                neg[e.to] = true;
            }
            if neg[e.from] == true{ neg[e.to] = true;}
        }
    }
    return neg;
}
fn mod_for_big_int(k:Vec<char>, C:usize)-> usize{
    let mut k_mod_C = 0;
    for i in 0..k.len(){
        k_mod_C = (k_mod_C*10+(k[i] as usize - 48) as usize)%C;
    }
    k_mod_C
}
/*
fn imos() {
    input!{
        n:usize,
        m:usize,
        q:usize,
        lr:[(usize, usize);m],
        pq:[(usize, usize);q],
    }
    let mut v = vec![vec![0;n+2];n+2];
    for i in 0..m{
        v[lr[i].0][lr[i].1] +=1;
    }
    
    for i in 1..n+2{
        for j in 1..n+2{

            v[i][j] +=v[i-1][j];
        }
    }
    for i in 1..n+2{
        for j in 1..n+2{

            v[i][j] +=v[i][j-1];
        }
    }
    for i in 0..q{
        println!("{}", v[pq[i].1][pq[i].1] - v[pq[i].0-1][pq[i].1] - v[pq[i].1][pq[i].0-1] + v[pq[i].0-1][pq[i].0-1] );
    }
}
*/
/*
fn main(){
    input!{
        n:usize,
        xy:[(usize, usize);n-1],
        q:usize,
        ab:[(usize, usize);q],
    }
    let MAX_DEPTH =1+ ( (100000 as f64 ).log2() ) as usize;
    let mut G:Vec<Vec<usize>> = Vec::new();
    let mut root = 1;
    let mut parent = vec![vec![0;n+1];MAX_DEPTH];
    let mut depth = vec![0;n+1];
    fn dfs(G:&Vec<Vec<usize>>,parent:&mut Vec<Vec<i64>>,depth:&mut Vec<i64>, v:i64, p:i64, d:i64){
        let v = v as usize;
        parent[0][v] = p as i64;
        depth[v] = d as i64;
        for i in 0..G[v].len(){
            if G[v][i] != p as usize{
                dfs(G, parent, depth, G[v][i] as i64, v as i64, d+1);
            }
        }
    }
    fn init(G:&Vec<Vec<usize>>, V:usize, root:usize, parent:&mut Vec<Vec<i64>>,depth:&mut Vec<i64>, MAX_DEPTH:usize){
        dfs(G,parent,depth, root as i64, -1, 0);
        for k in 0..(MAX_DEPTH+1){
            if k+1>=MAX_DEPTH{
                break;
            }

            for v in 0..V{
                if parent[k][v] < 0 { parent[k+1][v] = -1;}
                else{ parent[k+1][v] = parent[k][parent[k][v] as usize];}
            }
        }
    }
    fn lca(u:usize, v:usize, parent:& Vec<Vec<i64>>,depth:&Vec<i64>, MAX_DEPTH:usize) -> i64{
        let mut u = u.clone();
        let mut v = v.clone();
        let mut du = depth[u];
        let mut dv = depth[v];
        if depth[u] > depth[v]{mem::swap(&mut u, &mut v);}
        for k in 0..MAX_DEPTH{
            let shifted = (depth[v] - depth[u]) >> k;
            if (shifted & 1) == 1{
                v = parent[k][v] as usize;
            }
            if shifted == 0{
                break;
            }
        }
        //if u==v{return u as i64;}

        if u == v{ return (du-dv).abs() + 1;}
        for k in (0..MAX_DEPTH).rev(){
            if parent[k][u] != parent[k][v]{
                u = parent[k][u] as usize;
                v = parent[k][v] as usize;
            }
        }
        //return parent[0][u];
        let mut dd = 0;
        if parent[0][u] != -1{
            dd = depth[parent[0][u] as usize];
        }
        return du-dd*2+dv+1;
    }
    for i in 0..n+1{
        G.push(Vec::new());
    }
    for i in 0..n-1{
        G[xy[i].0].push(xy[i].1);
        G[xy[i].1].push(xy[i].0);
    }
    let mut parent = vec![vec![0;n+1];MAX_DEPTH];
    let mut depht = vec![0;n+1];
    init(&G, n+1, 1, &mut parent,&mut depth, MAX_DEPTH); 
    for i in 0..q{
        println!("{}", lca(ab[i].0, ab[i].1, &parent, &depth, MAX_DEPTH) );
        }



}
*/
fn main(){
    input!{
        n:usize,
        ma:usize,
        mb:usize,
        abc:[(usize,usize, usize);n],
    }
    let inf = 10000000000000;
    let mut dp = vec![vec![vec![10000000000000;1001];1001];101];
    dp[0][0][0] = 0;
    for i in 0..n{
        for j in 0..800{
            for k in 0..800{
                if j>=abc[i].0 && k>=abc[i].1{
                    dp[i+1][j][k] = cmp::min(dp[i][j][k], dp[i][j-abc[i].0][k-abc[i].1] + abc[i].2);
                }
            }
        }
    }
    let mut res = inf;
    for i in 1..400{
        let i1 = ma*i;
        let i2 = mb*i;
        if i1<=1000 && i2<=1000{
            res = cmp::min(dp[n][i1][i2], res);
        }
    }
    if inf != res{
        println!("{}", res);
    }
    else{
        println!("-1");
    }
}