import java.io.*;
import java.util.*;

import static java.lang.Math.*;
import static java.util.Arrays.*;

public class cf1342e {

    static int[] fact;

    public static void main(String[] args) throws IOException {
        int n = rni(), k, ans = 0, mult = 1;
        fact = new int[n + 1];
        ifact = new int[n + 1];
        long kl = nl();
        if(kl >= n) {
            prln(0);
            close();
            return;
        }
        k = (int)kl;
        fact[0] = fact[1] = 1;
        for(int i = 2; i <= n; ++i) {
            fact[i] = fmul(fact[i - 1], i);
        }
        for(int i = 0; i <= n - k; ++i, mult = -mult) {
            int add = mult * fmul(fpow(n - k - i, n), fmul(fact[n - k], fmul(ifact(i), ifact(n - k - i))));
            while(add < 0) {
                add += fmod;
            }
            ans += add;
            if(ans >= fmod) {
                ans -= fmod;
            }
        }
        ans = fmul(fmul(ans, fact[n]), fmul(ifact(k), ifact(n - k)));
        prln(k == 0 ? ans : fmul(ans, 2));
        close();
    }

    static int[] ifact;

    static int ifact(int x) {
        if(ifact[x] > 0) {
            return ifact[x];
        } else {
            return ifact[x] = fpow(fact[x], fmod - 2);
        }
    }

    static int fmod = 998244353;

    static int fpow(int a, int b) {
        if(a == 0) {
            return 0;
        }
        int ans = 1;
        while(b > 0) {
            if((b & 1) > 0) {
                ans = fmul(ans, a);
            }
            a = fmul(a, a);
            b >>= 1;
        }
        return ans;
    }

    static int fmul(int a, int b) {
        int ans = 0;
        while(b > 0) {
            if((b & 1) > 0) {
                ans += a;
                if(ans >= fmod) {
                    ans -= fmod;
                }
            }
            a <<= 1;
            if(a >= fmod) {
                a -= fmod;
            }
            b >>= 1;
        }
        return ans;
    }

    static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
    static StringTokenizer input;
    static Random rand = new Random();

    // references
    // IBIG = 1e9 + 7
    // IMAX ~= 2e10
    // LMAX ~= 9e18

    // constants
    static final int IBIG = 1000000007;
    static final int IMAX = 2147483647;
    static final int IMIN = -2147483648;
    static final long LMAX = 9223372036854775807L;
    static final long LMIN = -9223372036854775808L;
    // math util
    static int minof(int a, int b, int c) {return min(a, min(b, c));}
    static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
    static long minof(long a, long b, long c) {return min(a, min(b, c));}
    static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
    static int maxof(int a, int b, int c) {return max(a, max(b, c));}
    static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
    static long maxof(long a, long b, long c) {return max(a, max(b, c));}
    static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
    static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static int fli(double d) {return (int)d;}
    static int cei(double d) {return (int)ceil(d);}
    static long fll(double d) {return (long)d;}
    static long cel(double d) {return (long)ceil(d);}
    static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
    // array util
    static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
    static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
    static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
    static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void rsort(int[] a) {shuffle(a); sort(a);}
    static void rsort(long[] a) {shuffle(a); sort(a);}
    static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
    static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
    static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
    static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}
    static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}
    static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}
    static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}
    // graph util
    static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
    static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}
    static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);}
    static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}
    static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);}
    static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
    static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}
    static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}
    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}
    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}
    static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
    static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
    static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
    static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
    // input
    static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
    static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
    static long rl() throws IOException {return Long.parseLong(__in.readLine());}
    static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
    static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;}
    static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
    static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
    static String rline() throws IOException {return __in.readLine();}
    static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
    static int ni() {return Integer.parseInt(input.nextToken());}
    static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
    static long nl() {return Long.parseLong(input.nextToken());}
    // output
    static void pr(int i) {__out.print(i);}
    static void prln(int i) {__out.println(i);}
    static void pr(long l) {__out.print(l);}
    static void prln(long l) {__out.println(l);}
    static void pr(double d) {__out.print(d);}
    static void prln(double d) {__out.println(d);}
    static void pr(char c) {__out.print(c);}
    static void prln(char c) {__out.println(c);}
    static void pr(char[] s) {__out.print(new String(s));}
    static void prln(char[] s) {__out.println(new String(s));}
    static void pr(String s) {__out.print(s);}
    static void prln(String s) {__out.println(s);}
    static void pr(Object o) {__out.print(o);}
    static void prln(Object o) {__out.println(o);}
    static void prln() {__out.println();}
    static void pryes() {__out.println("yes");}
    static void pry() {__out.println("Yes");}
    static void prY() {__out.println("YES");}
    static void prno() {__out.println("no");}
    static void prn() {__out.println("No");}
    static void prN() {__out.println("NO");}
    static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
    static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
    static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
    static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
    static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
    static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
    static void h() {__out.println("hlfd");}
    static void flush() {__out.flush();}
    static void close() {__out.close();}
}


import java.io.*;
import java.util.*;

import static java.lang.Math.*;
import static java.util.Arrays.*;

public class cf1342e {

    public static void main(String[] args) throws IOException {
        int n = rni(), k, fact[] = new int[n + 1], ifact[] = new int[n + 2], ans = 0, mult = 1;
        long kl = nl();
        if(kl >= n) {
            prln(0);
            close();
            return;
        }
        k = (int)kl;
        fact[0] = fact[1] = ifact[0] = ifact[1] = 1;
        for(int i = 2; i <= n; ++i) {
            fact[i] = fmul(fact[i - 1], i);
            ifact[i] = fpow(fact[i], fmod - 2);
        }
        for(int i = 0; i <= n - k; ++i, mult = -mult) {
            int add = mult * fmul(fpow(n - k - i, n), fmul(fact[n - k], fmul(ifact[i], ifact[n - k - i])));
            while(add < 0) {
                add += fmod;
            }
            ans += add;
            if(ans >= fmod) {
                ans -= fmod;
            }
        }
        ans = fmul(fmul(ans, fact[n]), fmul(ifact[k], ifact[n - k]));
        prln(k == 0 ? ans : fmul(ans, 2));
        close();
    }

    static int fmod = 998244353;

    static int fpow(int a, int b) {
        if(a == 0) {
            return 0;
        }
        int ans = 1;
        while(b > 0) {
            if((b & 1) > 0) {
                ans = fmul(ans, a);
            }
            a = fmul(a, a);
            b >>= 1;
        }
        return ans;
    }

    static int fmul(int a, int b) {
        int ans = 0;
        while(b > 0) {
            if((b & 1) > 0) {
                ans += a;
                if(ans >= fmod) {
                    ans -= fmod;
                }
            }
            a <<= 1;
            if(a >= fmod) {
                a -= fmod;
            }
            b >>= 1;
        }
        return ans;
    }

    static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
    static StringTokenizer input;
    static Random rand = new Random();

    // references
    // IBIG = 1e9 + 7
    // IMAX ~= 2e10
    // LMAX ~= 9e18

    // constants
    static final int IBIG = 1000000007;
    static final int IMAX = 2147483647;
    static final int IMIN = -2147483648;
    static final long LMAX = 9223372036854775807L;
    static final long LMIN = -9223372036854775808L;
    // math util
    static int minof(int a, int b, int c) {return min(a, min(b, c));}
    static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
    static long minof(long a, long b, long c) {return min(a, min(b, c));}
    static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
    static int maxof(int a, int b, int c) {return max(a, max(b, c));}
    static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
    static long maxof(long a, long b, long c) {return max(a, max(b, c));}
    static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
    static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static int fli(double d) {return (int)d;}
    static int cei(double d) {return (int)ceil(d);}
    static long fll(double d) {return (long)d;}
    static long cel(double d) {return (long)ceil(d);}
    static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
    // array util
    static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
    static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
    static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
    static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void rsort(int[] a) {shuffle(a); sort(a);}
    static void rsort(long[] a) {shuffle(a); sort(a);}
    static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
    static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
    static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
    static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}
    static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}
    static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}
    static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}
    // graph util
    static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
    static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}
    static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);}
    static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}
    static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);}
    static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
    static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;}
    static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}
    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;}
    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}
    static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
    static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
    static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
    static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
    // input
    static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
    static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
    static long rl() throws IOException {return Long.parseLong(__in.readLine());}
    static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
    static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;}
    static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
    static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
    static String rline() throws IOException {return __in.readLine();}
    static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
    static int ni() {return Integer.parseInt(input.nextToken());}
    static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
    static long nl() {return Long.parseLong(input.nextToken());}
    // output
    static void pr(int i) {__out.print(i);}
    static void prln(int i) {__out.println(i);}
    static void pr(long l) {__out.print(l);}
    static void prln(long l) {__out.println(l);}
    static void pr(double d) {__out.print(d);}
    static void prln(double d) {__out.println(d);}
    static void pr(char c) {__out.print(c);}
    static void prln(char c) {__out.println(c);}
    static void pr(char[] s) {__out.print(new String(s));}
    static void prln(char[] s) {__out.println(new String(s));}
    static void pr(String s) {__out.print(s);}
    static void prln(String s) {__out.println(s);}
    static void pr(Object o) {__out.print(o);}
    static void prln(Object o) {__out.println(o);}
    static void prln() {__out.println();}
    static void pryes() {__out.println("yes");}
    static void pry() {__out.println("Yes");}
    static void prY() {__out.println("YES");}
    static void prno() {__out.println("no");}
    static void prn() {__out.println("No");}
    static void prN() {__out.println("NO");}
    static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
    static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
    static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
    static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
    static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
    static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
    static void h() {__out.println("hlfd");}
    static void flush() {__out.flush();}
    static void close() {__out.close();}
}


/*
 * Author Ayub Subhaniya
 * Institute DA-IICT
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Codeforces429D
{

	InputStream in;
	PrintWriter out;

	void solve()
	{
		long f=nl();
		long T=nl();
		long t0=nl();
		long a1,t1,p1,a2,t2,p2;
		a1=nl();t1=nl();p1=nl();
		a2=nl();t2=nl();p2=nl();

		long max1=(f+a1-1)/a1;
		long max2=(f+a2-1)/a2;
		long cost=Long.MAX_VALUE;

		if (t1<t2)
		{
			//tr("1");
			for (int k1=0;k1<=max1;k1++)
			{
				//tr(k1);
				long sz=f-k1*a1;
				if (sz<=0)
				{
					//tr(k1+" "+k1*p1);
					if (f*t1<=T)
						cost=Math.min(cost, k1*p1);
					break;
				}
				else
				{
					long l=0,r=(sz+a2-1)/a2,result=-1,t;
					while (l<=r)
					{
						long mid=((l+r)>>1);
						if (a2*mid>=sz)
							t=a1*k1*t1+sz*t2;
						else
							t=a1*k1*t1+a2*mid*t2+(sz-a2*mid)*t0;
						//tr(mid+" "+t);
						if (t<=T)
						{
							result=mid;
							r=mid-1;
						}
						else
						{
							l=mid+1;
						}
					}
					if (result!=-1)
					{
						cost=Math.min(cost, k1*p1+result*p2);
						//tr(k1+" "+k1*p1+result*p2);
					}
					//else
						//tr(k1+"-1");
				}
			}
		}
		else
		{
			//tr("2");
			for (int k2=0;k2<=max2;k2++)
			{
				//tr(k2);
				long sz=f-k2*a2;
				if (sz<=0)
				{
					//tr(k1+" "+k1*p1);
					if (f*t2<=T)
						cost=Math.min(cost, k2*p2);
					break;
				}
				else
				{
					long l=0,r=(sz+a1-a)/a1,result=-1,t;
					while (l<=r)
					{
						long mid=((l+r)>>1);
						if (a1*mid>=sz)
							t=a2*k2*t2+sz*t1;
						else
							t=a2*k2*t2+a1*mid*t1+(sz-a1*mid)*t0;
						//tr(mid+" "+t);
						if (t<=T)
						{
							result=mid;
							r=mid-1;
						}
						else
						{
							l=mid+1;
						}
					}
					if (result!=-1)
					{
						cost=Math.min(cost, k2*p2+result*p1);
						//tr(k2+" "+k2*p2+result*p1);
					}
					//else
						//tr(k2+"-1");
				}
			}
		}

		if (cost==Long.MAX_VALUE)
			out.println(-1);
		else
			out.println(cost);
	}

	void run() throws Exception
	{
		String INPUT = "C:/Users/ayubs/Desktop/input.txt";
		in = oj ? System.in : new FileInputStream(INPUT);
		out = new PrintWriter(System.out);
		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis() - s + "ms");

	}
	public static void main(String[] args) throws Exception
	{
		new Codeforces429D().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = in.read(inbuf);
			}
			catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean inSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && inSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(inSpaceChar(b)))
		{ // when nextLine, (inSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(inSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o)
	{
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

}


/*
 * Author Ayub Subhaniya
 * Institute DA-IICT
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Codeforces429D
{

	InputStream in;
	PrintWriter out;

	void solve()
	{
		long f=nl();
		long T=nl();
		long t0=nl();
		long a1,t1,p1,a2,t2,p2;
		a1=nl();t1=nl();p1=nl();
		a2=nl();t2=nl();p2=nl();

		long max1=(f+a1-1)/a1;
		long max2=(f+a2-1)/a2;
		long cost=Long.MAX_VALUE;
		//tr(max1,max2);
		//long ans1=-1,ans2=-1,tmp=71773335;
		//ans1=961250;ans2=897197;
		if (t1<t2)
		{
			//tr("1");
			for (long k1=0;k1<=max1;k1++)
			{
				//tr(k1);
				long sz=f-k1*a1;
				if (sz<=0)
				{
					//tr(k1+" "+k1*p1);
					if (f*t1<=T)
						cost=Math.min(cost, k1*p1);
					break;
				}
				else
				{
					long l=0,r=(sz+a2-1)/a2,result=-1,t=-1;
					while (l<=r)
					{
						long mid=((l+r)>>1);
						if (a2*mid>=sz)
							t=a1*k1*t1+sz*t2;
						else
							t=a1*k1*t1+a2*mid*t2+(sz-a2*mid)*t0;
						//if (k1==ans1&&mid==ans2)
							//tr(mid+" "+t);
						if (t<=T)
						{
							result=mid;
							r=mid-1;
						}
						else
						{
							l=mid+1;
						}
					}
					if (result!=-1)
					{
						cost=Math.min(cost, k1*p1+result*p2);
						//if (cost<tmp)
						//{
							//ans1=k1;ans2=result;
						//}
						//tr(k1+" "+k1*p1+result*p2);
					}
					//tmp=cost;
					//else
						//tr(k1+"-1");
					//if (cost==tmp)
					//{
						//tr(t);break;
					//}
				}
			}
			//tr(cost);
		}
		else
		{
			tr("2");
			for (long k2=0;k2<=max2;k2++)
			{
				//tr(k2);
				long sz=f-k2*a2;
				if (sz<=0)
				{
					//tr(k1+" "+k1*p1);
					if (f*t2<=T)
						cost=Math.min(cost, k2*p2);
					break;
				}
				else
				{
					long l=0,r=(sz+a1-1)/a1,result=-1,t;
					while (l<=r)
					{
						long mid=((l+r)>>1);
						if (a1*mid>=sz)
						{
							t=a2*k2*t2+sz*t1;
							//if(mid==ans1)
								//tr("hi");
						}
						else
							t=a2*k2*t2+a1*mid*t1+(sz-a1*mid)*t0;
						//if (k2==ans2)
							//tr(mid+" "+t);
						if (t<=T)
						{
							result=mid;
							r=mid-1;
						}
						else
						{
							l=mid+1;
						}
					}
					if (result!=-1)
					{
						cost=Math.min(cost, k2*p2+result*p1);
						//if (cost<tmp)
						//{
							//ans2=k2;ans1=result;
						//}
						//if (k2==ans2)
							//tr(k2+" "+k2*p2+result*p1);
					}
					//else if(k2==ans2)
						//tr(k2+"-1");
					//tmp=cost;
				}

			}
			//tr(cost);
		}
		//tr(ans1,ans2);

		if (cost==Long.MAX_VALUE)
			out.println(-1);
		else
			out.println(cost);
	}

	void run() throws Exception
	{
		String INPUT = "C:/Users/ayubs/Desktop/input.txt";
		in = oj ? System.in : new FileInputStream(INPUT);
		out = new PrintWriter(System.out);
		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis() - s + "ms");

	}
	public static void main(String[] args) throws Exception
	{
		new Codeforces429D().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = in.read(inbuf);
			}
			catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean inSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && inSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(inSpaceChar(b)))
		{ // when nextLine, (inSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(inSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o)
	{
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

}


/*
 * Author Ayub Subhaniya
 * Institute DA-IICT
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Codeforces429D
{

	InputStream in;
	PrintWriter out;

	void solve()
	{
		long f=nl();
		long T=nl();
		long t0=nl();
		long a1,t1,p1,a2,t2,p2;
		a1=nl();t1=nl();p1=nl();
		a2=nl();t2=nl();p2=nl();

		long max1=(f+a1-1)/a1;
		long max2=(f+a2-1)/a2;
		long cost=Long.MAX_VALUE;

		for (int k1=0;k1<=max1;k1++)
		{
			long sz=f-k1*a1;
			if (sz<=0)
			{
				//tr(k1+" "+k1*p1);
				if (f*t1<=T)
					cost=Math.min(cost, k1*p1);
			}
			else
			{
				long l=0,r=max2,result=-1,t;
				while (l<=r)
				{
					long mid=((l+r)>>1);
					if (a2*mid>=sz)
						t=a1*k1*t1+sz*t2;
					else
						t=a1*k1*t1+a2*mid*t2+(sz-a2*mid)*t0;

					if (t<=T)
					{
						result=mid;
						r=mid-1;
					}
					else
					{
						l=mid+1;
					}
				}
				if (result!=-1)
				{
					cost=Math.min(cost, k1*p1+result*p2);
					//tr(k1+" "+k1*p1+result*p2);
				}
				//else
					//tr(k1+"-1");
			}
		}
		if (cost==Long.MAX_VALUE)
			out.println(-1);
		else
			out.println(cost);
	}

	void run() throws Exception
	{
		String INPUT = "C:/Users/ayubs/Desktop/input.txt";
		in = oj ? System.in : new FileInputStream(INPUT);
		out = new PrintWriter(System.out);
		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis() - s + "ms");

	}
	public static void main(String[] args) throws Exception
	{
		new Codeforces429D().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = in.read(inbuf);
			}
			catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean inSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && inSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(inSpaceChar(b)))
		{ // when nextLine, (inSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(inSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o)
	{
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

}


/*
 * Author Ayub Subhaniya
 * Institute DA-IICT
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Codeforces429D
{

	InputStream in;
	PrintWriter out;

	long MAX=2*(long)1e14+7;
	void solve()
	{
		long f=nl();
		long T=nl();
		long t0=nl();
		long a1,t1,p1,a2,t2,p2;
		a1=nl();t1=nl();p1=nl();
		a2=nl();t2=nl();p2=nl();

		long max1=f/a1;
		long max2=f/a2;
		long cost=MAX;

		if (t1<t2)
		{
			//tr("1");
			for (int k1=0;k1<=max1;k1++)
			{
				//tr(k1);
				long sz=f-k1*a1;

				max2=(sz+a2-1)/a2;
				long l=0,r=sz/a2,result=-1,t;
				while (l<=r)
				{
					long mid=((l+r)>>1);

					t=a1*k1*t1+a2*mid*t2+(sz-a2*mid)*t0;
					//tr(mid+" "+t);
					if (t<=T)
					{
						result=mid;
						r=mid-1;
					}
					else
					{
						l=mid+1;
					}
				}
				t=a1*k1*t1+sz*t2;
				if (t<=T)
					cost=Math.min(cost, k1*p1+max2*p2);

				if (result!=-1)
				{
					cost=Math.min(cost, k1*p1+result*p2);
					//tr(k1+" "+k1*p1+result*p2);
				}
				//else
					//tr(k1+"-1");
			}
			max1=(f+a1-1)/a1;
			long t=f*t1;
			if (t<=T)
				cost=Math.min(cost, max1*p1);
		}
		else
		{
			//tr("2");
			for (int k2=0;k2<=max2;k2++)
			{
				//tr(k2);
				long sz=f-k2*a2;

				max1=(sz+a1-1)/a1;

				long l=0,r=sz/a1,result=-1,t;
				while (l<=r)
				{
					long mid=((l+r)>>1);

					t=a2*k2*t2+a1*mid*t1+(sz-a1*mid)*t0;
					//tr(mid+" "+t);
					if (t<=T)
					{
						result=mid;
						r=mid-1;
					}
					else
					{
						l=mid+1;
					}
				}

				t=a2*k2*t2+sz*t1;
				if (t<=T)
					cost=Math.min(cost, k2*p2+max1*p1);

				if (result!=-1)
				{
					cost=Math.min(cost, k2*p2+result*p1);
					//tr(k2+" "+k2*p2+result*p1);
				}
				//else
					//tr(k2+"-1");
			}
			max2=(f+a2-1)/a2;
			long t=f*t2;
			if (t<=T)
				cost=Math.min(cost, max2*p2);
		}

		if (cost==MAX)
			out.println(-1);
		else
			out.println(cost);
	}

	void run() throws Exception
	{
		String INPUT = "C:/Users/ayubs/Desktop/input.txt";
		in = oj ? System.in : new FileInputStream(INPUT);
		out = new PrintWriter(System.out);
		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis() - s + "ms");

	}
	public static void main(String[] args) throws Exception
	{
		new Codeforces429D().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = in.read(inbuf);
			}
			catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean inSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && inSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(inSpaceChar(b)))
		{ // when nextLine, (inSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(inSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			}
			else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o)
	{
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeSet;

public final class CF_325_AliceBob {

	void log(int[] X){
		int L=X.length;
		for (int i=0;i<L;i++){
			logWln(X[i]+" ");
		}
		log("");
	}

	void log(long[] X){
		int L=X.length;
		for (int i=0;i<L;i++){
			logWln(X[i]+" ");
		}
		log("");
	}
	void log(Object[] X){
		int L=X.length;
		for (int i=0;i<L;i++){
			logWln(X[i]+" ");
		}
		log("");
	}

	void log(Object o){
		logWln(o+"\n");
	}

	void logWln(Object o){
		System.out.print(o);
		//outputWln(o);

	}
	void info(Object o){
		System.out.println(o);
		//output(o);
	}

	void output(Object o){

		outputWln(""+o+"\n");

	}

	void outputWln(Object o){
		// System.out.print(o);

		try {
			out.write(""+ o);
		} catch (Exception e) {

		}
	}

	class Composite implements Comparable<Composite>{
		int x;
		int y;

		public int compareTo(Composite X){
			if (x!=X.x)
				return x-X.x;
			return y-X.y;
		}

		public Composite(int x, int y) {
			this.x = x;
			this.y = y;
		}

	}

	long pgcd(long a,long b){
		if (b>a)
			return pgcd(b,a);
		while (b>0){
			long c=b;
			b=a%b;
			a=c;
		}
		return a;
	}

	String solve(long x,long y){
		long p=pgcd(x,y);
		if (p!=1)
			return "Impossible";

		String res="";
		int cnt=0;
		char cur='Z';
		while (x>0 && y>0 && x!=y){

			if (y>x){

				y-=x;
				if (cur!='B'){
					if (cur=='A')
						res+=cnt+""+'A';
					cnt=1;
					cur='B';
				} else {
					cnt++;
				}

			} else {
				x-=y;
				if (cur!='A'){
					if (cur=='B')
						res+=cnt+""+'B';
					cnt=1;
					cur='A';
				} else {
					cnt++;
				}

			}

		}
		res+=cnt+""+cur;
		return res;
	}

	void simulate(){
		TreeSet<Composite> list=new TreeSet<Composite>();
		int LEN=5;
		int m=1<<LEN;
		for (int i=0;i<m;i++){
			int u=1,v=0,x=0,y=1;
			String st="";
			for (int e=0;e<LEN;e++){
				int mask=(1<<e)&i;
				if (mask==0){
					u+=x;
					v+=y;
					st+="A";
				} else {
					x+=u;
					y+=v;
					st+="B";
				}
				log((x+u)+" "+(v+y)+" "+st+" ///"+solve(x+u,v+y));
				list.add(new Composite(x+u,v+y));
			}
		}
		/*
		for (Composite X:list){
			log(X.x+" "+X.y);
		}
		 */
	}

	BufferedWriter out;

	void process() throws Exception {

		out = new BufferedWriter(new OutputStreamWriter(System.out));
		InputReader reader=new InputReader(System.in);

		long u=reader.readLong();

		long v=reader.readLong();

		output(solve(u,v));

		//simulate();
		/*
		long a=1,b=0;
		long x=0;y=1;
		boolean goon=true;
		while (goon){
			String s=reader.readString();
			if (s.charAt(0)=='A'){
				x+=a;
				y+=b;
			} else {
				a+=x;
				b+=y;
			}
			log("Alice:"+a+" "+b+" // Bob:"+x+" "+y+" // total :"+(a+x)+" "+(b+y));
		}
		 */
		try {
			out.close();
		}
		catch (Exception e){}

	}

	public static void main(String[] args) throws Exception {
		CF_325_AliceBob J=new CF_325_AliceBob();

		J.process();

	}

	static final class InputReader {
		private final InputStream stream;
		private final byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		private int read() throws IOException {
			if (curChar >= numChars) {
				curChar = 0;
				numChars = stream.read(buf);
				if (numChars <= 0) {
					return -1;
				}
			}
			return buf[curChar++];
		}

		public final String readString() throws IOException {
			int c = read();
			while (isSpaceChar(c)) {
				c = read();
			}
			StringBuilder res=new StringBuilder();
			do {
				res.append((char)c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public final int readInt() throws IOException {
			int c = read();
			boolean neg=false;
			while (isSpaceChar(c)) {
				c = read();
			}
			char d=(char)c;
			//log("d:"+d);
			if (d=='-') {
				neg=true;
				c = read();
			}
			int res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			//log("res:"+res);
			if (neg)
				return -res;
			return res;

		}

		public final long readLong() throws IOException {
			int c = read();
			boolean neg=false;
			while (isSpaceChar(c)) {
				c = read();
			}
			char d=(char)c;
			//log("d:"+d);
			if (d=='-') {
				neg=true;
				c = read();
			}
			long res = 0;
			do {
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			//log("res:"+res);
			if (neg)
				return -res;
			return res;

		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}
	}

}


import java.math.BigInteger;
import java.util.Scanner;

public class E {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		long x = scan.nextLong();
		long y = scan.nextLong();
		if(gcd(x,y) != 1) {
			System.out.println("Impossible");
			return;
		}
		long a = 1, b = 0;
		long c = 0, d = 1;
		int dir = 0;
		if(x > y) {
			dir = 1;
		}
		StringBuilder ans = new StringBuilder();
		while((a+c) != x || (b+d) != y) {
			//long lo = 1;
			//long hi = 1_000_000_000_000_000_001L;
			//while(lo < hi) {
			//
			//}
			if(dir == 0) {
				BigInteger num = BigInteger.valueOf(x).multiply(BigInteger.valueOf(b).add(BigInteger.valueOf(d))).subtract(BigInteger.valueOf(y).multiply(BigInteger.valueOf(c).add(BigInteger.valueOf(a))));
				BigInteger den = BigInteger.valueOf(c).multiply(BigInteger.valueOf(y)).subtract(BigInteger.valueOf(x).multiply(BigInteger.valueOf(d)));
				BigInteger div = num.divide(den);//num.add(den.subtract(BigInteger.ONE)).divide(den);
				long k = div.longValue();
				//System.out.println("dir = 0, k = " + k);
				a += k*c;
				b += k*d;
				ans.append(k).append("B");
			} else {
				a = a ^ c ^ (c = a);
				b = b ^ d ^ (d = b);
				BigInteger num = BigInteger.valueOf(x).multiply(BigInteger.valueOf(b).add(BigInteger.valueOf(d))).subtract(BigInteger.valueOf(y).multiply(BigInteger.valueOf(c).add(BigInteger.valueOf(a))));
				BigInteger den = BigInteger.valueOf(c).multiply(BigInteger.valueOf(y)).subtract(BigInteger.valueOf(x).multiply(BigInteger.valueOf(d)));
				BigInteger div = num.add(den.subtract(BigInteger.ONE)).divide(den);
				long k = div.longValue();
				//System.out.println("dir = 1, k = " + k);
				a += k*c;
				b += k*d;
				a = a ^ c ^ (c = a);
				b = b ^ d ^ (d = b);
				ans.append(k).append("A");
			}
			//System.out.println("at (" + a + "/" + b +"), (" + c + "/" + d + ") = " + (a+c) + "/" + (b+d));
			dir = 1-dir;
			//break;
		}
		System.out.println(ans);

	}
	static long gcd(long a, long b) {
		if(b == 0) return a;
		return gcd(b,a%b);
	}
	public static int compare(long a, long b, long c, long d) {
		BigInteger left = BigInteger.valueOf(a).multiply(BigInteger.valueOf(d));
		BigInteger right = BigInteger.valueOf(c).multiply(BigInteger.valueOf(b));
		return left.compareTo(right);
	}
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 *
 * @author pttrung
 */
public class C_Round_325_Div1 {

	public static long MOD = 1000000007;

	public static void main(String[] args) throws FileNotFoundException {
		// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
		// "output.txt")));
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();
		long x = in.nextLong();
		long y = in.nextLong();
		if (x == y) {

			out.println("Impossible");

		} else {
			String v = cal(new Point(1, 0), new Point(0, 1), x, y);
			if (v == null) {
				out.println("Impossible");
			} else {
				out.println(v);
			}
		}
		out.close();
	}

	static String cal(Point a, Point b, long x, long y) {
		//System.out.println(a.x + " " + a.y + " " + b.x + " " + b.y);
		if (a.x  == x && a.y  == y) {
			return "";
		} else if (b.x == x && b.y == y) {
			return "";
		} else if (a.x + b.x > x || a.y + b.y > y) {
			return null;
		}
		int c = crossProduct(a.x, a.y, x, y);
		int d = crossProduct(b.x, b.y, x, y);

		int f = crossProduct(a.x + b.x, a.y + b.y, x, y);
		boolean removeA = d !=f;
		//System.out.println(c + " " + d + " " + f);
		long s = 0;
		long e = 10000000000000L;
		long result = -1;
		while (s <= e) {
			long mid = (s + e) / 2;

			if (removeA) {
				if(a.x + mid*b.x <= 0 || a.y + mid*b.y <= 0){
					e = mid - 1;
					continue;
				}
				int v = crossProduct(a.x + mid * b.x, a.y + mid * b.y, x, y);

				if (v == d) {

					e = mid - 1;
				} else {
					if (result == -1 || result < mid) {
						result = mid;
					}
					s = mid + 1;
				}
			} else {
				if(b.x + mid*a.x <= 0 || b.y + mid*a.y <= 0){
					e = mid - 1;
					continue;
				}
				int v = crossProduct(b.x + mid * a.x, b.y + mid * a.y, x, y);
				// System.out.println(v + " " + mid);
				if (v == c) {

					e = mid - 1;
				} else {
					if (result == -1 || result < mid) {
						result = mid;
					}
					s = mid + 1;
				}
			}
		}
//		if (true) {
			//System.out.println(result);
//			return "";
//		}
		String tmp = null;
		if (removeA) {
			tmp = cal(new Point(a.x + result * b.x, a.y + result * b.y), b, x,
					y);
		} else {
			tmp = cal(a, new Point(b.x + result * a.x, b.y + result * a.y), x,
					y);
		}
		if (tmp != null) {
			return (result - (tmp.isEmpty() ? 1 : 0)) + (removeA ? "B" : "A")
					+ tmp;
		}
		return null;

	}

	static int crossProduct(long x, long y, long x1, long y1) {
		BigInteger a = BigInteger.valueOf(x);
		a = a.multiply(BigInteger.valueOf(y1));
		BigInteger b = BigInteger.valueOf(y);
		b = b.multiply(BigInteger.valueOf(x1));

		return a.compareTo(b);
	}

	public static int[] KMP(String val) {
		int i = 0;
		int j = -1;
		int[] result = new int[val.length() + 1];
		result[0] = -1;
		while (i < val.length()) {
			while (j >= 0 && val.charAt(j) != val.charAt(i)) {
				j = result[j];
			}
			j++;
			i++;
			result[i] = j;
		}
		return result;

	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	public static int digit(long n) {
		int result = 0;
		while (n > 0) {
			n /= 10;
			result++;
		}
		return result;
	}

	public static double dist(long a, long b, long x, long y) {
		double val = (b - a) * (b - a) + (x - y) * (x - y);
		val = Math.sqrt(val);
		double other = x * x + a * a;
		other = Math.sqrt(other);
		return val + other;

	}

	public static class Point {

		long x, y;

		public Point(long start, long end) {
			this.x = start;
			this.y = end;
		}

	}

	public static class FT {

		long[] data;

		FT(int n) {
			data = new long[n];
		}

		public void update(int index, long value) {
			while (index < data.length) {
				data[index] += value;
				index += (index & (-index));
			}
		}

		public long get(int index) {
			long result = 0;
			while (index > 0) {
				result += data[index];
				index -= (index & (-index));
			}
			return result;

		}
	}

	public static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	public static long pow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b == 1) {
			return a;
		}
		long val = pow(a, b / 2);
		if (b % 2 == 0) {
			return val * val % MOD;
		} else {
			return val * (val * a % MOD) % MOD;

		}
	}

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("input.txt"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public String nextLine() {
			st = null;
			try {
				return br.readLine();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}


import java.math.*;
import java.io.*;
import java.util.*;
public class C586E{
   public static long[] cAr, div;
   public static int N,M,K;
   public static int[] numCycle;
   public static Map<Integer,Set<Integer>> map;
   public static long MOD = 1000000007;
   public static void main(String[] args) throws IOException{
      InputReader in=new InputReader(new InputStreamReader(System.in));
      PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out));
      long[] ar=in.nextLongAr();
      long A=ar[0]; long B=ar[1];
      if(gcd(A,B)!=1) System.out.println("Impossible");
      else{
         while(A+B>1){
            if((A-1)/B > 0) System.out.print(((A-1)/B)+"A");
            A%=B;
            if((B-1)/A > 0) System.out.print(((B-1)/A)+"B");
            B%=A;
         }
      }
   }

   public static long gcd(long x,long y){
      BigInteger a = BigInteger.valueOf(x);
      BigInteger b = BigInteger.valueOf(y);
      BigInteger gcd = a.gcd(b);
      return gcd.longValue();
   }

   public static void setUpChoose(int t){
      cAr=new long[t+1];
      div=new long[t+1];
      cAr[0]=1;
      div[0]=1;

      for(int x=1;x<=t;x++){
         cAr[x]=(x*cAr[x-1])%(MOD);
         div[x]=pow(cAr[x],MOD-2);}
   }

   public static long choose(int x,int y){
      long a=cAr[x+y];
      long b=div[x];
      long c=div[y];
      a=(a*b)%MOD;
      a=(a*c)%MOD;
      return a;
   }

   public static long pow(long a,long b){
      if(b==1)
         return a;
      long c=b/2;
      long temp=pow(a,c)%MOD;
      temp=(temp*temp)%MOD;
      if(b%2==1) temp=temp*a;
      return temp%MOD;
   }
}

class InputReader{
   private BufferedReader br;
   public InputReader(InputStreamReader in){
      br=new BufferedReader(in);
   }
   public int nextInt(){
      try{
         return Integer.parseInt(br.readLine());}
      catch(IOException e){throw new InputMismatchException();}
   }
   public int[] nextIntAr(){
      try{
         String[] s=br.readLine().split(" ");
         int[] ret=new int[s.length];
         for(int x=0;x<s.length;x++)
            ret[x]=Integer.parseInt(s[x]);
         return ret;}

      catch(IOException e){throw new InputMismatchException();}
   }

   public long nextLong(){
      try{
         return Long.parseLong(br.readLine());}
      catch(IOException e){throw new InputMismatchException();}
   }
   public long[] nextLongAr(){
      try{
         String[] s=br.readLine().split(" ");
         long[] ret=new long[s.length];
         for(int x=0;x<s.length;x++)
            ret[x]=Long.parseLong(s[x]);
         return ret;}

      catch(IOException e){throw new InputMismatchException();}
   }

   public String[] nextStringAr(){
      try{
         return br.readLine().split(" ");}

      catch(IOException e){throw new InputMismatchException();}
   }

   public String nextString(){
      try{
         return br.readLine();}

      catch(IOException e){throw new InputMismatchException();}
   }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
3 3 5
0 1 1 0 7
1 1 1 0 10
1 1 1 1 2
1 1 1 2 2
0 1 1 2 3

500 500 2
0 1 1 0 4
0 1 1 1 2

500 500 8
100 100 5 5 1
100 101 5 5 2
101 100 5 5 3
101 101 5 5 4
100 100 6 5 5
100 101 6 5 6
101 100 6 5 7
101 101 6 5 8

6 7 6
0 2 2 2 100
0 3 3 3 100
0 2 2 1 201
0 3 3 2 5
1 2 1 3 1000
1 2 1 2 1000
200

6 7 6
0 2 2 2 100
0 3 3 3 100
0 2 2 1 194
0 3 3 2 5
1 2 1 3 1000
1 2 1 2 1000
199

6 7 6
1 2 2 3 100
1 3 3 4 100
1 2 2 2 194
1 3 3 3 5
2 2 1 4 1000
2 2 1 3 1000
0
 */
public class C {

	static long[][] costOf;
	static BonusAtSquare[][] hBonuses, vBonuses;
	static int maxX, maxY;
	static long[][][][] dp;

	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		maxX=fs.nextInt();
		maxY=fs.nextInt();
		int nRobots=fs.nextInt();
		costOf=new long[maxX][maxY];
		hBonuses=new BonusAtSquare[maxX][maxY];
		vBonuses=new BonusAtSquare[maxX][maxY];
		for (int x=0; x<maxX; x++)
			for (int y=0; y<maxY; y++) {
				hBonuses[x][y]=new BonusAtSquare();
				vBonuses[x][y]=new BonusAtSquare();
			}

		for (int i=0; i<nRobots; i++) {
			int x=fs.nextInt(), y=fs.nextInt(), d=fs.nextInt(), t=fs.nextInt();
			long killCost=fs.nextInt();
			processTransformer(x, y, d, t, killCost);
		}
		long startTime=System.currentTimeMillis();
		dp=new long[2][maxY+1][511][2];
		for (int i=0; i<dp.length; i++)
			for (int j=0; j<dp[i].length; j++)
				for (int k=0; k<dp[i][j].length; k++)
					Arrays.fill(dp[i][j][k], -1);
		for (int xAt=maxX-1; xAt>=0; xAt--) {
			for (int j=0; j<dp[0].length; j++)
				for (int k=0; k<dp[0][j].length; k++)
					Arrays.fill(dp[(xAt&1)][j][k], -1);

			for (int yAt=maxY-1; yAt>=0; yAt--) {
				for (int goingH=0; goingH<2; goingH++) {
					for (int timesGoingStraight=0; timesGoingStraight<=(goingH==0?xAt:yAt); timesGoingStraight++) {
						go(xAt, yAt, timesGoingStraight, goingH);
					}
				}
			}
		}
		long ans=go(0, 0, 0, 0);
		System.out.println(ans);
		System.err.println(System.currentTimeMillis()-startTime);
	}

	static long go(int x, int y, int timesGoingStraight, int goingH) {
		if (x==maxX-1&&y==maxY-1) {
			return 0;
		}
		if (dp[(x&1)][y][timesGoingStraight][goingH]!=-1) return dp[(x&1)][y][timesGoingStraight][goingH];
		long curCost=costOf[x][y];
		if (goingH==1)
			curCost-=hBonuses[x][y].getBonus(timesGoingStraight);
		else
			curCost-=vBonuses[x][y].getBonus(timesGoingStraight);
//		System.out.println("Cur cost "+x+" "+y+" is "+curCost);
		long best;
		if (goingH==1) {
			long goH=y+1<maxY?go(x, y+1, timesGoingStraight+1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, 1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
		else {
			long goH=y+1<maxY?go(x, y+1, 1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, timesGoingStraight+1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
//		System.out.println(x+" "+y+" "+timesGoingStraight+" "+goingH);
		return dp[(x&1)][y][timesGoingStraight][goingH]=best;
	}

	//have to process these in increasing straight distance
	static class BonusAtSquare {
		PriorityQueue<Bonus> pq=new PriorityQueue<>();
		public long bonusAdded=0;

		public void addBonus(int goingStraightFor, long bonus) {
			pq.add(new Bonus(goingStraightFor, bonus));
		}

		public long getBonus(int goingStraightFor) {
			while (!pq.isEmpty()&&goingStraightFor>=pq.peek().goingStraightFor) {
				Bonus next=pq.remove();
				bonusAdded+=next.points;
			}
			return bonusAdded;
		}
	}

	static class Bonus implements Comparable<Bonus> {
		int goingStraightFor;
		long points;
		public Bonus(int goingStraightFor, long points) {
			this.goingStraightFor=goingStraightFor;
			this.points=points;
		}

		public int compareTo(Bonus o) {
			return Integer.compare(goingStraightFor, o.goingStraightFor);
		}
	}

	static void processTransformer(int x, int y, int d, int t, long fightCost) {
//		System.out.println("Processing transformer ("+x+", "+y+") d: "+d+" startTime: "+t+" fightCost: "+fightCost);
		int[] xs=new int[4];
		int[] ys=new int[4];
		int[] firstTime=new int[4];
		xs[0]=x;
		ys[0]=y;
		firstTime[0]=t;
		xs[1]=x+d;
		ys[1]=y-d;
		firstTime[1]=t+1;
		xs[2]=x+d;
		ys[2]=y;
		firstTime[2]=t+2;
		xs[3]=x;
		ys[3]=y+d;
		firstTime[3]=t+3;

		ArrayList<Integer> xMatters=new ArrayList<>();
		ArrayList<Integer> yMatters=new ArrayList<>();
		for (int i=0; i<4; i++) {
			if (matters(xs[i], ys[i], firstTime[i])) {
				xMatters.add(xs[i]);
				yMatters.add(ys[i]);
			}
		}
//		System.out.println("\t"+xMatters+" "+yMatters);
		if (xMatters.size()>2) throw null;
		if (xMatters.size()==0) return;
		if (xMatters.size()==1) {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
		}
		else {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
			costOf[xMatters.get(1)][yMatters.get(1)]+=fightCost;
			if (xMatters.get(0)==(int)xMatters.get(1)) {
				hBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
			}
			else {
				if (yMatters.get(0)==(int)yMatters.get(1)) {
					vBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
				}
			}
		}
	}

	static boolean matters(int x, int y, int t) {
		if (x+y<t) return false;
		if ((t-x-y)%4!=0) return false;
		return true;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		public String next() {
			whilimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
3 3 5
0 1 1 0 7
1 1 1 0 10
1 1 1 1 2
1 1 1 2 2
0 1 1 2 3

500 500 2
0 1 1 0 4
0 1 1 1 2

500 500 8
100 100 5 5 1
100 101 5 5 2
101 100 5 5 3
101 101 5 5 4
100 100 6 5 5
100 101 6 5 6
101 100 6 5 7
101 101 6 5 8

6 7 6
0 2 2 2 100
0 3 3 3 100
0 2 2 1 201
0 3 3 2 5
1 2 1 3 1000
1 2 1 2 1000
200

6 7 6
0 2 2 2 100
0 3 3 3 100
0 2 2 1 194
0 3 3 2 5
1 2 1 3 1000
1 2 1 2 1000
199

6 7 6
1 2 2 3 100
1 3 3 4 100
1 2 2 2 194
1 3 3 3 5
2 2 1 4 1000
2 2 1 3 1000
0
 */
public class C {

	static long[][] costOf;
	static BonusAtSquare[][] hBonuses, vBonuses;
	static int maxX, maxY;
	static long[][][][] dp;

	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		maxX=fs.nextInt();
		maxY=fs.nextInt();
		int nRobots=fs.nextInt();
		costOf=new long[maxX][maxY];
		hBonuses=new BonusAtSquare[maxX][maxY];
		vBonuses=new BonusAtSquare[maxX][maxY];
		for (int x=0; x<maxX; x++)
			for (int y=0; y<maxY; y++) {
				hBonuses[x][y]=new BonusAtSquare();
				vBonuses[x][y]=new BonusAtSquare();
			}

		for (int i=0; i<nRobots; i++) {
			int x=fs.nextInt(), y=fs.nextInt(), d=fs.nextInt(), t=fs.nextInt();
			long killCost=fs.nextInt();
			processTransformer(x, y, d, t, killCost);
		}
		long startTime=System.currentTimeMillis();
		dp=new long[2][maxY+1][511][2];
		for (int i=0; i<dp.length; i++)
			for (int j=0; j<dp[i].length; j++)
				for (int k=0; k<dp[i][j].length; k++)
					Arrays.fill(dp[i][j][k], -1);
		for (int xAt=maxX-1; xAt>=0; xAt--) {
			for (int j=0; j<dp[0].length; j++)
				for (int k=0; k<dp[0][j].length; k++)
					Arrays.fill(dp[(xAt&1)][j][k], -1);

			for (int yAt=maxY-1; yAt>=0; yAt--) {
				for (int goingH=0; goingH<2; goingH++) {
					for (int timesGoingStraight=0; timesGoingStraight<=(goingH==0?xAt:yAt); timesGoingStraight++) {
						go(xAt, yAt, timesGoingStraight, goingH);
					}
				}
			}
		}
		long ans=go(0, 0, 0, 0);
		System.out.println(ans);
		System.err.println(System.currentTimeMillis()-startTime);
	}

	static long go(int x, int y, int timesGoingStraight, int goingH) {
		if (x==maxX-1&&y==maxY-1) {
			return 0;
		}
		if (dp[(x&1)][y][timesGoingStraight][goingH]!=-1) return dp[(x&1)][y][timesGoingStraight][goingH];
		long curCost=costOf[x][y];
		if (goingH==1)
			curCost-=hBonuses[x][y].getBonus(timesGoingStraight);
		else
			curCost-=vBonuses[x][y].getBonus(timesGoingStraight);
//		System.out.println("Cur cost "+x+" "+y+" is "+curCost);
		long best;
		if (goingH==1) {
			long goH=y+1<maxY?go(x, y+1, timesGoingStraight+1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, 1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
		else {
			long goH=y+1<maxY?go(x, y+1, 1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, timesGoingStraight+1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
//		System.out.println(x+" "+y+" "+timesGoingStraight+" "+goingH);
		return dp[(x&1)][y][timesGoingStraight][goingH]=best;
	}

	//have to process these in increasing straight distance
	static class BonusAtSquare {
		PriorityQueue<Bonus> pq=new PriorityQueue<>();
		public long bonusAdded=0;

		public void addBonus(int goingStraightFor, long bonus) {
			pq.add(new Bonus(goingStraightFor, bonus));
		}

		public long getBonus(int goingStraightFor) {
			while (!pq.isEmpty()&&goingStraightFor>=pq.peek().goingStraightFor) {
				Bonus next=pq.remove();
				bonusAdded+=next.points;
			}
			return bonusAdded;
		}
	}

	static class Bonus implements Comparable<Bonus> {
		int goingStraightFor;
		long points;
		public Bonus(int goingStraightFor, long points) {
			this.goingStraightFor=goingStraightFor;
			this.points=points;
		}

		public int compareTo(Bonus o) {
			return Integer.compare(goingStraightFor, o.goingStraightFor);
		}
	}

	static void processTransformer(int x, int y, int d, int t, long fightCost) {
//		System.out.println("Processing transformer ("+x+", "+y+") d: "+d+" startTime: "+t+" fightCost: "+fightCost);
		int[] xs=new int[4];
		int[] ys=new int[4];
		int[] firstTime=new int[4];
		xs[0]=x;
		ys[0]=y;
		firstTime[0]=t;
		xs[1]=x+d;
		ys[1]=y-d;
		firstTime[1]=t+1;
		xs[2]=x+d;
		ys[2]=y;
		firstTime[2]=t+2;
		xs[3]=x;
		ys[3]=y+d;
		firstTime[3]=t+3;

		ArrayList<Integer> xMatters=new ArrayList<>();
		ArrayList<Integer> yMatters=new ArrayList<>();
		for (int i=0; i<4; i++) {
			if (matters(xs[i], ys[i], firstTime[i])) {
				xMatters.add(xs[i]);
				yMatters.add(ys[i]);
			}
		}
//		System.out.println("\t"+xMatters+" "+yMatters);
		if (xMatters.size()>2) throw null;
		if (xMatters.size()==0) return;
		if (xMatters.size()==1) {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
		}
		else {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
			costOf[xMatters.get(1)][yMatters.get(1)]+=fightCost;
			if (xMatters.get(0)==(int)xMatters.get(1)) {
				hBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
			}
			else {
				if (yMatters.get(0)==(int)yMatters.get(1)) {
					vBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
				}
			}
		}
	}

	static boolean matters(int x, int y, int t) {
		if (x+y<t) return false;
		if ((t-x-y)%4!=0) return false;
		return true;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		public String next() {
			while (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return st.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}
	}

}
e (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return st.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
3 3 5
0 1 1 0 7
1 1 1 0 10
1 1 1 1 2
1 1 1 2 2
0 1 1 2 3

500 500 2
0 1 1 0 4
0 1 1 1 2

 */
public class C {

	static long[][] costOf;
	static BonusAtSquare[][] hBonuses, vBonuses;
	static int maxX, maxY;
	static long[][][][] dp;

	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		maxX=fs.nextInt();
		maxY=fs.nextInt();
		int nRobots=fs.nextInt();
		costOf=new long[maxX][maxY];
		hBonuses=new BonusAtSquare[maxX][maxY];
		vBonuses=new BonusAtSquare[maxX][maxY];
		for (int x=0; x<maxX; x++)
			for (int y=0; y<maxY; y++) {
				hBonuses[x][y]=new BonusAtSquare();
				vBonuses[x][y]=new BonusAtSquare();
			}

		for (int i=0; i<nRobots; i++) {
			int x=fs.nextInt(), y=fs.nextInt(), d=fs.nextInt(), t=fs.nextInt();
			long killCost=fs.nextInt();
			processTransformer(x, y, d, t, killCost);
		}
		long startTime=System.currentTimeMillis();
		dp=new long[2][maxY+1][511][2];
		for (int i=0; i<dp.length; i++)
			for (int j=0; j<dp[i].length; j++)
				for (int k=0; k<dp[i][j].length; k++)
					Arrays.fill(dp[i][j][k], -1);
		for (int xAt=maxX-1; xAt>=0; xAt--) {
			for (int j=0; j<dp[0].length; j++)
				for (int k=0; k<dp[0][j].length; k++)
					Arrays.fill(dp[xAt%2][j][k], -1);

			for (int yAt=maxY-1; yAt>=0; yAt--) {
				for (int goingH=0; goingH<2; goingH++) {
					for (int timesGoingStraight=0; timesGoingStraight<(goingH==0?xAt:yAt); timesGoingStraight++) {
						go(xAt, yAt, timesGoingStraight, goingH);
					}
				}
			}
		}
		long ans=go(0, 0, 0, 0);
		System.out.println(ans);
		System.err.println(System.currentTimeMillis()-startTime);
	}

	static long go(int x, int y, int timesGoingStraight, int goingH) {
		if (x==maxX-1&&y==maxY-1) {
			return 0;
		}
		if (dp[x%2][y][timesGoingStraight][goingH]!=-1) return dp[x%2][y][timesGoingStraight][goingH];
		long curCost=costOf[x][y];
		if (goingH==1)
			curCost-=hBonuses[x][y].getBonus(timesGoingStraight);
		else
			curCost-=vBonuses[x][y].getBonus(timesGoingStraight);
//		System.out.println("Cur cost "+x+" "+y+" is "+curCost);
		long best;
		if (goingH==1) {
			long goH=y+1<maxY?go(x, y+1, timesGoingStraight+1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, 1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
		else {
			long goH=y+1<maxY?go(x, y+1, 1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, timesGoingStraight+1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
//		System.out.println(x+" "+y+" "+timesGoingStraight+" "+goingH);
		return dp[x%2][y][timesGoingStraight][goingH]=best;
	}

	//have to process these in increasing straight distance
	static class BonusAtSquare {
		PriorityQueue<Bonus> pq=new PriorityQueue<>();
		public long bonusAdded=0;

		public void addBonus(int goingStraightFor, long bonus) {
			pq.add(new Bonus(goingStraightFor, bonus));
		}

		public long getBonus(int goingStraightFor) {
			while (!pq.isEmpty()&&goingStraightFor>=pq.peek().goingStraightFor) {
				Bonus next=pq.remove();
				bonusAdded+=next.points;
			}
			return bonusAdded;
		}
	}

	static class Bonus implements Comparable<Bonus> {
		int goingStraightFor;
		long points;
		public Bonus(int goingStraightFor, long points) {
			this.goingStraightFor=goingStraightFor;
			this.points=points;
		}

		public int compareTo(Bonus o) {
			return Integer.compare(goingStraightFor, o.goingStraightFor);
		}
	}

	static void processTransformer(int x, int y, int d, int t, long fightCost) {
		int[] xs=new int[4];
		int[] ys=new int[4];
		int[] firstTime=new int[4];
		xs[0]=x;
		ys[0]=y;
		firstTime[0]=t;
		xs[1]=x+d;
		ys[1]=y-d;
		firstTime[1]=t+1;
		xs[2]=x+d;
		ys[2]=y;
		firstTime[2]=t+2;
		xs[3]=x;
		ys[3]=y+d;
		firstTime[3]=t+3;

		ArrayList<Integer> xMatters=new ArrayList<>();
		ArrayList<Integer> yMatters=new ArrayList<>();
		for (int i=0; i<4; i++) {
			if (matters(xs[i], ys[i], firstTime[i])) {
				xMatters.add(xs[i]);
				yMatters.add(ys[i]);
			}
		}
		if (xMatters.size()>2) throw null;
		if (xMatters.size()==0) return;
		if (xMatters.size()==1) {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
		}
		else {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
			costOf[xMatters.get(1)][yMatters.get(1)]+=fightCost;
			if (xMatters.get(0)==(int)xMatters.get(1)) {
				hBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
			}
			else {
				if (yMatters.get(0)!=(int)yMatters.get(1)) throw null;
				vBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
			}
		}
	}

	static boolean matters(int x, int y, int t) {
		if (x+y<t) return false;
		if ((t-x-y)%4!=0) return false;
		return true;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		public String next() {
			while (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return st.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
3 3 5
0 1 1 0 7
1 1 1 0 10
1 1 1 1 2
1 1 1 2 2
0 1 1 2 3

500 500 2
0 1 1 0 4
0 1 1 1 2

500 500 8
100 100 5 5 1
100 101 5 5 2
101 100 5 5 3
101 101 5 5 4
100 100 6 5 5
100 101 6 5 6
101 100 6 5 7
101 101 6 5 8
 */
public class C {

	static long[][] costOf;
	static BonusAtSquare[][] hBonuses, vBonuses;
	static int maxX, maxY;
	static long[][][][] dp;

	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		maxX=fs.nextInt();
		maxY=fs.nextInt();
		int nRobots=fs.nextInt();
		costOf=new long[maxX][maxY];
		hBonuses=new BonusAtSquare[maxX][maxY];
		vBonuses=new BonusAtSquare[maxX][maxY];
		for (int x=0; x<maxX; x++)
			for (int y=0; y<maxY; y++) {
				hBonuses[x][y]=new BonusAtSquare();
				vBonuses[x][y]=new BonusAtSquare();
			}

		for (int i=0; i<nRobots; i++) {
			int x=fs.nextInt(), y=fs.nextInt(), d=fs.nextInt(), t=fs.nextInt();
			long killCost=fs.nextInt();
			processTransformer(x, y, d, t, killCost);
		}
		long startTime=System.currentTimeMillis();
		dp=new long[2][maxY+1][511][2];
		for (int i=0; i<dp.length; i++)
			for (int j=0; j<dp[i].length; j++)
				for (int k=0; k<dp[i][j].length; k++)
					Arrays.fill(dp[i][j][k], -1);
		for (int xAt=maxX-1; xAt>=0; xAt--) {
			for (int j=0; j<dp[0].length; j++)
				for (int k=0; k<dp[0][j].length; k++)
					Arrays.fill(dp[xAt%2][j][k], -1);

			for (int yAt=maxY-1; yAt>=0; yAt--) {
				for (int goingH=0; goingH<2; goingH++) {
					for (int timesGoingStraight=0; timesGoingStraight<=(goingH==0?xAt:yAt); timesGoingStraight++) {
						go(xAt, yAt, timesGoingStraight, goingH);
					}
				}
			}
		}
		long ans=go(0, 0, 0, 0);
		System.out.println(ans);
		System.err.println(System.currentTimeMillis()-startTime);
	}

	static long go(int x, int y, int timesGoingStraight, int goingH) {
		if (x==maxX-1&&y==maxY-1) {
			return 0;
		}
		if (dp[x%2][y][timesGoingStraight][goingH]!=-1) return dp[x%2][y][timesGoingStraight][goingH];
		long curCost=costOf[x][y];
		if (goingH==1)
			curCost-=hBonuses[x][y].getBonus(timesGoingStraight);
		else
			curCost-=vBonuses[x][y].getBonus(timesGoingStraight);
//		System.out.println("Cur cost "+x+" "+y+" is "+curCost);
		long best;
		if (goingH==1) {
			long goH=y+1<maxY?go(x, y+1, timesGoingStraight+1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, 1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
		else {
			long goH=y+1<maxY?go(x, y+1, 1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, timesGoingStraight+1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
//		System.out.println(x+" "+y+" "+timesGoingStraight+" "+goingH);
		return dp[x%2][y][timesGoingStraight][goingH]=best;
	}

	//have to process these in increasing straight distance
	static class BonusAtSquare {
		PriorityQueue<Bonus> pq=new PriorityQueue<>();
		public long bonusAdded=0;

		public void addBonus(int goingStraightFor, long bonus) {
			pq.add(new Bonus(goingStraightFor, bonus));
		}

		public long getBonus(int goingStraightFor) {
			while (!pq.isEmpty()&&goingStraightFor>=pq.peek().goingStraightFor) {
				Bonus next=pq.remove();
				bonusAdded+=next.points;
			}
			return bonusAdded;
		}
	}

	static class Bonus implements Comparable<Bonus> {
		int goingStraightFor;
		long points;
		public Bonus(int goingStraightFor, long points) {
			this.goingStraightFor=goingStraightFor;
			this.points=points;
		}

		public int compareTo(Bonus o) {
			return Integer.compare(goingStraightFor, o.goingStraightFor);
		}
	}

	static void processTransformer(int x, int y, int d, int t, long fightCost) {
//		System.out.println("Processing transformer ("+x+", "+y+") d: "+d+" startTime: "+t+" fightCost: "+fightCost);
		int[] xs=new int[4];
		int[] ys=new int[4];
		int[] firstTime=new int[4];
		xs[0]=x;
		ys[0]=y;
		firstTime[0]=t;
		xs[1]=x+d;
		ys[1]=y-d;
		firstTime[1]=t+1;
		xs[2]=x+d;
		ys[2]=y;
		firstTime[2]=t+2;
		xs[3]=x;
		ys[3]=y+d;
		firstTime[3]=t+3;

		ArrayList<Integer> xMatters=new ArrayList<>();
		ArrayList<Integer> yMatters=new ArrayList<>();
		for (int i=0; i<4; i++) {
			if (matters(xs[i], ys[i], firstTime[i])) {
				xMatters.add(xs[i]);
				yMatters.add(ys[i]);
			}
		}
//		System.out.println("\t"+xMatters+" "+yMatters);
		if (xMatters.size()>2) throw null;
		if (xMatters.size()==0) return;
		if (xMatters.size()==1) {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
		}
		else {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
			costOf[xMatters.get(1)][yMatters.get(1)]+=fightCost;
			if (xMatters.get(0)==(int)xMatters.get(1)) {
				hBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
			}
			else {
				if (yMatters.get(0)!=(int)yMatters.get(1)) {
					vBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
				}
			}
		}
	}

	static boolean matters(int x, int y, int t) {
		if (x+y<t) return false;
		if ((t-x-y)%4!=0) return false;
		return true;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		public String next() {
			while (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return st.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
3 3 5
0 1 1 0 7
1 1 1 0 10
1 1 1 1 2
1 1 1 2 2
0 1 1 2 3

500 500 2
0 1 1 0 4
0 1 1 1 2

500 500 8
100 100 5 5 1
100 101 5 5 2
101 100 5 5 3
101 101 5 5 4
100 100 6 5 5
100 101 6 5 6
101 100 6 5 7
101 101 6 5 8

6 7 6
0 2 2 2 100
0 3 3 3 100
0 2 2 1 201
0 3 3 2 5
1 2 1 3 1000
1 2 1 2 1000
200

6 7 6
0 2 2 2 100
0 3 3 3 100
0 2 2 1 194
0 3 3 2 5
1 2 1 3 1000
1 2 1 2 1000
199

6 7 6
1 2 2 3 100
1 3 3 4 100
1 2 2 2 194
1 3 3 3 5
2 2 1 4 1000
2 2 1 3 1000
0
 */
public class C {

	static long[][] costOf;
	static BonusAtSquare[][] hBonuses, vBonuses;
	static int maxX, maxY;
	static long[][][][] dp;

	public static void main(String[] args) {
		FastScanner fs=new FastScanner();
		maxX=fs.nextInt();
		maxY=fs.nextInt();
		int nRobots=fs.nextInt();
		costOf=new long[maxX][maxY];
		hBonuses=new BonusAtSquare[maxX][maxY];
		vBonuses=new BonusAtSquare[maxX][maxY];
		for (int x=0; x<maxX; x++)
			for (int y=0; y<maxY; y++) {
				hBonuses[x][y]=new BonusAtSquare();
				vBonuses[x][y]=new BonusAtSquare();
			}

		for (int i=0; i<nRobots; i++) {
			int x=fs.nextInt(), y=fs.nextInt(), d=fs.nextInt(), t=fs.nextInt();
			long killCost=fs.nextInt();
			processTransformer(x, y, d, t, killCost);
		}
		long startTime=System.currentTimeMillis();
		dp=new long[2][maxY+1][511][2];
		for (int i=0; i<dp.length; i++)
			for (int j=0; j<dp[i].length; j++)
				for (int k=0; k<dp[i][j].length; k++)
					Arrays.fill(dp[i][j][k], -1);
		for (int xAt=maxX-1; xAt>=0; xAt--) {
			for (int j=0; j<dp[0].length; j++)
				for (int k=0; k<dp[0][j].length; k++)
					Arrays.fill(dp[xAt%2][j][k], -1);

			for (int yAt=maxY-1; yAt>=0; yAt--) {
				for (int goingH=0; goingH<2; goingH++) {
					for (int timesGoingStraight=0; timesGoingStraight<=(goingH==0?xAt:yAt); timesGoingStraight++) {
						go(xAt, yAt, timesGoingStraight, goingH);
					}
				}
			}
		}
		long ans=go(0, 0, 0, 0);
		System.out.println(ans);
		System.err.println(System.currentTimeMillis()-startTime);
	}

	static long go(int x, int y, int timesGoingStraight, int goingH) {
		if (x==maxX-1&&y==maxY-1) {
			return 0;
		}
		if (dp[x%2][y][timesGoingStraight][goingH]!=-1) return dp[x%2][y][timesGoingStraight][goingH];
		long curCost=costOf[x][y];
		if (goingH==1)
			curCost-=hBonuses[x][y].getBonus(timesGoingStraight);
		else
			curCost-=vBonuses[x][y].getBonus(timesGoingStraight);
//		System.out.println("Cur cost "+x+" "+y+" is "+curCost);
		long best;
		if (goingH==1) {
			long goH=y+1<maxY?go(x, y+1, timesGoingStraight+1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, 1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
		else {
			long goH=y+1<maxY?go(x, y+1, 1, 1):Long.MAX_VALUE;
			long goV=x+1<maxX?go(x+1, y, timesGoingStraight+1, 0):Long.MAX_VALUE;
			best=Math.min(goH, goV)+curCost;
		}
//		System.out.println(x+" "+y+" "+timesGoingStraight+" "+goingH);
		return dp[x%2][y][timesGoingStraight][goingH]=best;
	}

	//have to process these in increasing straight distance
	static class BonusAtSquare {
		PriorityQueue<Bonus> pq=new PriorityQueue<>();
		public long bonusAdded=0;

		public void addBonus(int goingStraightFor, long bonus) {
			pq.add(new Bonus(goingStraightFor, bonus));
		}

		public long getBonus(int goingStraightFor) {
			while (!pq.isEmpty()&&goingStraightFor>=pq.peek().goingStraightFor) {
				Bonus next=pq.remove();
				bonusAdded+=next.points;
			}
			return bonusAdded;
		}
	}

	static class Bonus implements Comparable<Bonus> {
		int goingStraightFor;
		long points;
		public Bonus(int goingStraightFor, long points) {
			this.goingStraightFor=goingStraightFor;
			this.points=points;
		}

		public int compareTo(Bonus o) {
			return Integer.compare(goingStraightFor, o.goingStraightFor);
		}
	}

	static void processTransformer(int x, int y, int d, int t, long fightCost) {
//		System.out.println("Processing transformer ("+x+", "+y+") d: "+d+" startTime: "+t+" fightCost: "+fightCost);
		int[] xs=new int[4];
		int[] ys=new int[4];
		int[] firstTime=new int[4];
		xs[0]=x;
		ys[0]=y;
		firstTime[0]=t;
		xs[1]=x+d;
		ys[1]=y-d;
		firstTime[1]=t+1;
		xs[2]=x+d;
		ys[2]=y;
		firstTime[2]=t+2;
		xs[3]=x;
		ys[3]=y+d;
		firstTime[3]=t+3;

		ArrayList<Integer> xMatters=new ArrayList<>();
		ArrayList<Integer> yMatters=new ArrayList<>();
		for (int i=0; i<4; i++) {
			if (matters(xs[i], ys[i], firstTime[i])) {
				xMatters.add(xs[i]);
				yMatters.add(ys[i]);
			}
		}
//		System.out.println("\t"+xMatters+" "+yMatters);
		if (xMatters.size()>2) throw null;
		if (xMatters.size()==0) return;
		if (xMatters.size()==1) {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
		}
		else {
			costOf[xMatters.get(0)][yMatters.get(0)]+=fightCost;
			costOf[xMatters.get(1)][yMatters.get(1)]+=fightCost;
			if (xMatters.get(0)==(int)xMatters.get(1)) {
				hBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
			}
			else {
				if (yMatters.get(0)==(int)yMatters.get(1)) {
					vBonuses[xMatters.get(1)][yMatters.get(1)].addBonus(d, fightCost);
				}
			}
		}
	}

	static boolean matters(int x, int y, int t) {
		if (x+y<t) return false;
		if ((t-x-y)%4!=0) return false;
		return true;
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		public String next() {
			while (!st.hasMoreElements())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return st.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}
	}

}


//package codeforces;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class C {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(System.out);
    StringTokenizer stringTokenizer;

    String next() throws IOException {
        while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
            stringTokenizer = new StringTokenizer(reader.readLine());
        }
        return stringTokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    void solve() throws IOException {
        int n = nextInt();
        int m = nextInt();
        char[][] map = new char[n][];
        int bombs = 0;
        int treasures = 0;
        for (int i = 0; i < n; i++) {
            map[i] = next().toCharArray();
            for (int j = 0; j < m; j++) {
                if (map[i][j] == 'B') bombs++;
                if (map[i][j] >= '0' && map[i][j] <= '9') {
                    treasures++;
                    map[i][j]--;
                }
            }
        }
        int[] treasureCosts = new int[treasures];
        for (int i = 0; i < treasures; i++) {
            treasureCosts[i] = nextInt();
        }
        class Point {
            int x, y;

            Point(int x, int y) {
                this.x = x;
                this.y = y;
            }

            Point subtract(Point other) {
                return new Point(x - other.x, y - other.y);
            }

            int vectorProduct(Point other) {
                return x * other.y - y * other.x;
            }

            Point add(Point other) {
                return new Point(x + other.x, y + other.y);
            }
        }
        class GeomUtils {
            Point cellCenter(int row, int column) {
                return new Point(2 * row + 1, 2 * column + 1);
            }

            Point ray = new Point(40, 41);

            double getT(Point o, Point v, Point s1, Point s2) {
                Point vs = s2.subtract(s1);
                int r = vs.vectorProduct(s2) - vs.vectorProduct(o);
                int l = vs.vectorProduct(v);
                return 1.0 * r / l;
            }

            boolean intersects(Point o, Point s1, Point s2) {
                if (getT(o, ray, s1, s2) < 0.0) return false;
                double t = getT(s1, s2.subtract(s1), o, o.add(ray));
                return t >= 0.0 && t <= 1.0;
            }
        }
        Point[] treasureCoords = new Point[treasures];
        Point[] bombCoords = new Point[bombs];
        bombs = 0;
        int si = 0, sj = 0;
        GeomUtils geomUtils = new GeomUtils();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (map[i][j] == 'B') {
                    bombCoords[bombs++] = geomUtils.cellCenter(i, j);
                }
                if (map[i][j] >= '0' && map[i][j] <= '9') {
                    treasureCoords[map[i][j] - '0'] = geomUtils.cellCenter(i, j);
                }
                if (map[i][j] == 'S') {
                    si = i;
                    sj = j;
                }
            }
        }
        int[][][][] dist = new int[n][m][1 << treasures][1 << bombs];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                for (int k = 0; k < 1 << treasures; k++)
                    for (int l = 0; l < 1 << bombs; l++) dist[i][j][k][l] = Integer.MAX_VALUE;
        dist[si][sj][0][0] = 0;
        Queue<Integer> qi = new LinkedList<>(), qj = new LinkedList<>(), qt = new LinkedList<>(), qb = new LinkedList<>();
        qi.add(si);
        qj.add(sj);
        qt.add(0);
        qb.add(0);
        int[] di = {0, -1, 0, 1};
        int[] dj = {-1, 0, 1, 0};
        while (!qi.isEmpty()) {
            int i = qi.poll();
            int j = qj.poll();
            int tmask = qt.poll();
            int bmask = qb.poll();
            Point s1 = geomUtils.cellCenter(i, j);
            for (int k = 0; k < 4; k++) {
                int ii = i + di[k];
                int jj = j + dj[k];
                if (ii < 0 || ii >= n || jj < 0 || jj >= m || map[ii][jj] != '.' && map[ii][jj] != 'S') continue;
                int tm = 0;
                for (int ti = 0; ti < treasures; ti++) {
                    if (geomUtils.intersects(treasureCoords[ti], s1, geomUtils.cellCenter(ii, jj))) {
                        tm |= 1 << ti;
                    }
                }
                int bm = 0;
                for (int bi = 0; bi < bombs; bi++) {
                    if (geomUtils.intersects(bombCoords[bi], s1, geomUtils.cellCenter(ii, jj))) {
                        bm |= 1 << bi;
                    }
                }
                if (dist[ii][jj][tmask ^ tm][bmask ^ bm] == Integer.MAX_VALUE) {
                    dist[ii][jj][tmask ^ tm][bmask ^ bm] = dist[i][j][tmask][bmask] + 1;
                    qi.add(ii);
                    qj.add(jj);
                    qt.add(tmask ^ tm);
                    qb.add(bmask ^ bm);
                }
            }
        }
        int ans = 0;
        for (int i = 0; i < 1 << treasures; i++) {
            int tCost = 0;
            for (int j = 0; j < treasures; j++) {
                if (((i >> j) & 1) == 1) tCost += treasureCosts[j];
            }
            ans = Math.max(ans, tCost - dist[si][sj][i][0]);
        }
        writer.println(ans);
        writer.close();
    }

    public static void main(String[] args) throws IOException {
        new C().solve();
    }
}


//package round221;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;

public class C {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni(), m = ni();
		char[][] map = nm(n,m);
		int sr = -1, sc = -1;
		int[][] objs = new int[8][];
		int p = 0;
		int max = 0;
		for(int i = 0;i < n;i++){
			for(int j = 0;j < m;j++){
				if(map[i][j] == 'S'){
					sr = i; sc = j;
					map[sr][sc] = '.';
				}
				if(map[i][j] >= '1' && map[i][j] <= '9'){
					objs[p++] = new int[]{i, j, map[i][j]-'0'};
					max = Math.max(max, map[i][j]-'0');
				}
				if(map[i][j] == 'B'){
					objs[p++] = new int[]{i, j, -99999};
				}
			}
		}
		int[] price = na(max);
		for(int i = 0;i < p;i++){
			if(objs[i][2] >= 0){
				objs[i][2] = price[objs[i][2]-1];
			}
		}

		int I = 999999;
		int[][][][] d = new int[n][m][1<<p][3];
		for(int i = 0;i < n;i++){
			for(int j = 0;j < m;j++){
				for(int k = 0;k < 1<<p;k++){
					Arrays.fill(d[i][j][k], I);
				}
			}
		}
		d[sr][sc][0][1] = 0;
		Queue<Integer> q = new ArrayDeque<Integer>();
		q.add(enc(sr, sc, 1, 0));
		int[] dr = { 1, 0, -1, 0 };
		int[] dc = { 0, 1, 0, -1 };
		while(!q.isEmpty()){
			int cur = q.poll();
			int r = cur>>>5&31, c = cur&31, ptn = cur>>>12, predir = cur>>>10&3;
			for(int k = 0;k < 4;k++){
				int nr = r + dr[k], nc = c + dc[k];
				if(nr >= 0 && nr < n && nc >= 0 && nc < m && map[nr][nc] == '.'){
					int nptn = ptn;
					if((k == 2 || k == 0) && k != 2-predir){
						for(int u = 0;u < p;u++){
							if(objs[u][0] == r && objs[u][1] < c)nptn ^= 1<<u;
						}
					}
					int npredir = k == 0 || k == 2 ? k : predir;
					if(d[nr][nc][nptn][npredir] > d[r][c][ptn][predir] + 1){
						d[nr][nc][nptn][npredir] = d[r][c][ptn][predir] + 1;
						q.add(enc(nr, nc, npredir, nptn));
					}
				}
			}
		}

		long ret = 0;
		for(int i = 0;i < 1<<p;i++){
			long tot = 0;
			for(int j = 0;j < p;j++){
				if(i<<31-j<0){
					tot += objs[j][2];
				}
			}
			for(int k = 0;k < 3;k++){
				ret = Math.max(ret, tot - d[sr][sc][i][k]);
			}
		}
		out.println(ret);
	}

	int enc(int r, int c, int predir, int ptn)
	{
		return ptn<<12|predir<<10|r<<5|c;
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new C().run(); }

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}