import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import java.util.Queue;

import static java.lang.Math.max;
import static java.lang.Math.min;

public class C implements Runnable{

    // SOLUTION!!!
    // HACK ME PLEASE IF YOU CAN!!!
    // PLEASE!!!
    // PLEASE!!!
    // PLEASE!!!

    private final static Random rnd = new Random(222);
    private final static String fileName = "";

    private final static long MODULO = 1000 * 1000 * 1000 + 7;

    final int MAX_RND = 10000000;

    private void solve1() {
        for (int it = 0; it < 10; ++it) {
            int need = rnd.nextInt(MAX_RND) + 1;
            long maxTime = rnd.nextInt(MAX_RND) + 1;
            long freeDefaultTime = rnd.nextInt(MAX_RND) + 1;

            int firstDefaultSize = rnd.nextInt(MAX_RND) + 1;
            long firstDefaultTime = rnd.nextInt(MAX_RND) + 1;
            long firstDefaultCost = rnd.nextInt(MAX_RND) + 1;

            int secondDefaultSize = rnd.nextInt(MAX_RND) + 1;
            long secondDefaultTime = rnd.nextInt(MAX_RND) + 1;
            long secondDefaultCost = rnd.nextInt(MAX_RND) + 1;

            long answer = getAnswer(need, maxTime, freeDefaultTime,
                    firstDefaultSize, firstDefaultTime, firstDefaultCost,
                    secondDefaultSize, secondDefaultTime, secondDefaultCost);

            long bruteAnswer = getBruteAnswer(need, maxTime, freeDefaultTime,
                    firstDefaultSize, firstDefaultTime, firstDefaultCost,
                    secondDefaultSize, secondDefaultTime, secondDefaultCost);

            if (answer != bruteAnswer) {
                System.err.println("GOTCHA");

                System.err.println(need + " " + maxTime + " " +firstDefaultTime);
                System.err.println(firstDefaultSize + " " + firstDefaultTime + " " +firstDefaultCost);
                System.err.println(secondDefaultSize + " " + secondDefaultTime + " " +secondDefaultCost);
            }
        }
    }

    private void solve() {
        int need = readInt();
        long maxTime = readInt();
        long freeDefaultTime = readInt();

        int firstDefaultSize = readInt();
        long firstDefaultTime = readInt();
        long firstDefaultCost = readInt();

        int secondDefaultSize = readInt();
        long secondDefaultTime = readInt();
        long secondDefaultCost = readInt();

//        long[] firstTimes = new long[need + 1];
//        long[] firstCosts = new long[need + 1];
//
//        for (int i = 1; i <= need; i += firstDefaultSize) {
//            firstTimes[i] = firstDefaultTime + (i == 1 ? 0 : firstTimes[i - firstDefaultSize]);
//            firstCosts[i] = firstDefaultCost + (i == 1 ? 0 : firstCosts[i - firstDefaultSize]);
//        }
//
//        for (int i = 1; i <= need; ++i) {
//            firstTimes[i] = max(firstTimes[i - 1], firstTimes[i]);
//            firstCosts[i] = max(firstCosts[i - 1], firstCosts[i]);
//        }
//
//        long[] secondTimes = new long[need + 1];
//        long[] secondCosts = new long[need + 1];
//
//        for (int i = 1; i <= need; i += secondDefaultSize) {
//            secondTimes[i] = secondDefaultTime + (i == 1 ? 0 : secondTimes[i - secondDefaultSize]);
//            secondCosts[i] = secondDefaultCost + (i == 1 ? 0 : secondCosts[i - secondDefaultSize]);
//        }
//
//        for (int i = 1; i <= need; ++i) {
//            secondTimes[i] = max(secondTimes[i - 1], secondTimes[i]);
//            secondCosts[i] = max(secondCosts[i - 1], secondCosts[i]);
//        }
//
//        long[] freeTimes = new long[need + 1];
//        for (int i = 1; i <= need; ++i) {
//            freeTimes[i] = freeTimes[i - 1] + freeDefaultTime;
//        }

        long answer = getBruteAnswer(need, maxTime, freeDefaultTime,
                firstDefaultSize, firstDefaultTime, firstDefaultCost,
                secondDefaultSize, secondDefaultTime, secondDefaultCost
        );

        out.println(answer);
    }

    long getAnswer(int need, long maxTime, long freeDefaultTime,
                   int firstDefaultSize,long firstDefaultTime,long firstDefaultCost,
                   int secondDefaultSize,long secondDefaultTime,long secondDefaultCost) {
        long answer = Long.MAX_VALUE;

        long firstTime = 0, firstCost = 0;
        for (int firstCount = 0, firstSize = 0; ;
             ++firstCount, firstSize += firstDefaultSize,
            firstCost += firstDefaultCost,
                     firstTime += firstDefaultTime * firstDefaultSize) {

            if (firstSize >= need) {
                firstSize = need;
                firstTime = firstDefaultTime * firstSize;
            }

            long canUseTime = maxTime - firstTime;
            int needUseSize = need - firstSize;
            if (canUseTime >= 0) {
                if (freeDefaultTime <= secondDefaultTime) {
                    long freeTime = freeDefaultTime * needUseSize;
                    if (freeTime + firstTime <= maxTime) {
                        answer = min(answer, firstCost);
                    }
                } else {
                    int lowerSideCount = needUseSize / secondDefaultSize;
                    int lowerSecondSize = secondDefaultSize * lowerSideCount;
                    int lowerFreeSize = needUseSize - lowerSecondSize;

                    long lowerSecondTime = lowerSecondSize * secondDefaultTime;
                    long lowerFreeTime = lowerFreeSize * freeDefaultTime;

                    if (lowerSecondTime + lowerFreeTime <= canUseTime) {
                        answer = min(answer, firstCost + lowerSideCount * secondDefaultCost);
                    }

                    int upperSideCount = needUseSize / secondDefaultSize;
                    if (needUseSize % secondDefaultSize != 0) ++upperSideCount;
                    int upperSecondSize = min(needUseSize, secondDefaultSize * upperSideCount);
                    int upperFreeSize = needUseSize - upperSecondSize;

                    long upperSecondTime = upperSecondSize * secondDefaultTime;
                    long upperFreeTime = upperFreeSize * freeDefaultTime;

                    if (upperSecondTime + upperFreeTime <= canUseTime) {
                        answer = min(answer, firstCost + upperSideCount * secondDefaultCost);
                    }

                    long exactNumerator = ((needUseSize * firstDefaultTime - canUseTime));
                    long exactDenominator = (freeDefaultTime - secondDefaultTime) * secondDefaultSize;

                    long exactSideCount = exactNumerator / exactDenominator;
                    if (exactNumerator < 0) exactSideCount = 0;
                    else if (exactNumerator % exactDenominator != 0) {
                        exactSideCount++;
                    }
                    if (exactSideCount >= 0) {
                        long exactSecondSize = min(needUseSize, secondDefaultSize * exactSideCount);
                        long exactFreeSize = needUseSize - exactSecondSize;

                        long exactSecondTime = exactSecondSize * secondDefaultTime;
                        long exactFreeTime = exactFreeSize * freeDefaultTime;

                        if (exactSecondTime + exactFreeTime <= canUseTime) {
                            answer = min(answer, firstCost + exactSideCount * secondDefaultCost);
                        }
                    }
                }
            }

            if (firstSize >= need) break;
        }

        if (answer == Long.MAX_VALUE) {
            answer = -1;
        }

        return answer;
    }

    long getBruteAnswer(int need, long maxTime, long freeDefaultTime,
                        int firstDefaultSize,long firstDefaultTime,long firstDefaultCost,
                        int secondDefaultSize,long secondDefaultTime,long secondDefaultCost) {
        long answer = Long.MAX_VALUE;

        for (int firstCount = 0; ; ++firstCount) {
            int firstSize = min(need, firstCount * firstDefaultSize);
            if (firstSize >= need) firstSize = need;

            long firstTime = firstSize * firstDefaultTime;
            long firstCost = firstCount * firstDefaultCost;

            int needUseSize = (need - firstSize);
            for (int secondCount = 0; ; ++secondCount) {
                int secondSize = min(needUseSize, secondCount * secondDefaultSize);
                if (secondSize >= needUseSize) secondSize = needUseSize;

                long secondTime = secondSize * secondDefaultTime;
                long secondCost = secondCount * secondDefaultCost;

                int freeSize = needUseSize - secondSize;
                long freeTime = freeSize * freeDefaultTime;

                if (firstTime + secondTime + freeTime <= maxTime) {
                    answer = min(answer, firstCost + secondCost);
                }

                if (secondSize >= needUseSize) break;
            }

            if (firstSize >= need) break;
        }

        if (answer == Long.MAX_VALUE) {
            answer = -1;
        }

        return answer;
    }

    /////////////////////////////////////////////////////////////////////

    private static long add(long a, long b) { return (a + b) % MODULO; }
    private static long subtract(long a, long b) { return add(a, MODULO - b) % MODULO; }
    private static long mult(long a, long b) { return (a * b) % MODULO; }

    /////////////////////////////////////////////////////////////////////

    private final static boolean FIRST_INPUT_STRING = false;
    private final static boolean MULTIPLE_TESTS = true;
    private final boolean ONLINE_JUDGE = !new File("input.txt").exists();
//    private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    private final static int MAX_STACK_SIZE = 128;

    private final static boolean OPTIMIZE_READ_NUMBERS = false;

    /////////////////////////////////////////////////////////////////////

    public void run(){
        try{
            timeInit();
            Locale.setDefault(Locale.US);

            init();

            if (ONLINE_JUDGE) {
                solve();
            } else {
                do {
                    try {
                        timeInit();
                        solve();
                        time();

                        out.println();
                    } catch (NumberFormatException e) {
                        break;
                    } catch (NullPointerException e) {
                        if (FIRST_INPUT_STRING) break;
                        else throw e;
                    }
                } while (MULTIPLE_TESTS);
            }

            out.close();
            time();
        }catch (Exception e){
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private BufferedReader in;
    private OutputWriter out;
    private StringTokenizer tok = new StringTokenizer("");

    public static void main(String[] args){
        new Thread(null, new C(), "", MAX_STACK_SIZE * (1L << 20)).start();
    }

    /////////////////////////////////////////////////////////////////////

    private void init() throws FileNotFoundException{
        Locale.setDefault(Locale.US);

        if (ONLINE_JUDGE){
            if (fileName.isEmpty()) {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new OutputWriter(System.out);
            } else {
                in = new BufferedReader(new FileReader(fileName + ".in"));
                out = new OutputWriter(fileName + ".out");
            }
        }else{
            in = new BufferedReader(new FileReader("input.txt"));
            out = new OutputWriter("output.txt");
        }
    }

    ////////////////////////////////////////////////////////////////

    private long timeBegin;

    private void timeInit() {
        this.timeBegin = System.currentTimeMillis();
    }

    private void time(){
        long timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    private void debug(Object... objects){
        if (ONLINE_JUDGE){
            for (Object o: objects){
                System.err.println(o.toString());
            }
        }
    }

    /////////////////////////////////////////////////////////////////////

    private String delim = " ";

    private String readLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    private String readString() {
        try {
            while(!tok.hasMoreTokens()){
                tok = new StringTokenizer(readLine(), delim);
            }

            return tok.nextToken(delim);
        } catch (NullPointerException e) {
            return null;
        }
    }

    /////////////////////////////////////////////////////////////////

    private final char NOT_A_SYMBOL = '\0';

    private char readChar() {
        try {
            int intValue = in.read();

            if (intValue == -1){
                return NOT_A_SYMBOL;
            }

            return (char) intValue;
        } catch (IOException e) {
            throw new RuntimeIOException(e);
        }
    }

    private char[] readCharArray() {
        return readLine().toCharArray();
    }

    private char[][] readCharField(int rowsCount) {
        char[][] field = new char[rowsCount][];
        for (int row = 0; row < rowsCount; ++row) {
            field[row] = readCharArray();
        }

        return field;
    }

    /////////////////////////////////////////////////////////////////

    private long optimizedReadLong() {
        int sign = 1;
        long result = 0;
        boolean started = false;
        while (true) {
            try {
                int j = in.read();
                if (-1 == j) {
                    if (started) return sign * result;
                    throw new NumberFormatException();
                }

                if (j == '-') {
                    if (started) throw new NumberFormatException();
                    sign = -sign;
                }

                if ('0' <= j && j <= '9') {
                    result = result * 10 + j - '0';
                    started = true;
                } else if (started) {
                    return sign * result;
                }
            } catch (IOException e) {
                throw new RuntimeIOException(e);
            }
        }
    }

    private int readInt() {

        if (!OPTIMIZE_READ_NUMBERS) {
            return Integer.parseInt(readString());
        } else {
            return (int) optimizedReadLong();
        }
    }

    private int[] readIntArray(int size) {
        int[] array = new int[size];

        for (int index = 0; index < size; ++index){
            array[index] = readInt();
        }

        return array;
    }

    private int[] readSortedIntArray(int size) {
        Integer[] array = new Integer[size];

        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    private int[] readIntArrayWithDecrease(int size) {
        int[] array = readIntArray(size);

        for (int i = 0; i < size; ++i) {
            array[i]--;
        }

        return array;
    }

    ///////////////////////////////////////////////////////////////////

    private int[][] readIntMatrix(int rowsCount, int columnsCount) {
        int[][] matrix = new int[rowsCount][];

        for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
            matrix[rowIndex] = readIntArray(columnsCount);
        }

        return matrix;
    }

    private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
        int[][] matrix = new int[rowsCount][];

        for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
            matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
        }

        return matrix;
    }

    ///////////////////////////////////////////////////////////////////

    private long readLong() {
        if (!OPTIMIZE_READ_NUMBERS) {
            return Long.parseLong(readString());
        } else {
            return optimizedReadLong();
        }
    }

    private long[] readLongArray(int size) {
        long[] array = new long[size];

        for (int index = 0; index < size; ++index){
            array[index] = readLong();
        }

        return array;
    }

    ////////////////////////////////////////////////////////////////////

    private double readDouble() {
        return Double.parseDouble(readString());
    }

    private double[] readDoubleArray(int size) {
        double[] array = new double[size];

        for (int index = 0; index < size; ++index){
            array[index] = readDouble();
        }

        return array;
    }

    ////////////////////////////////////////////////////////////////////

    private BigInteger readBigInteger() {
        return new BigInteger(readString());
    }

    private BigDecimal readBigDecimal() {
        return new BigDecimal(readString());
    }

    /////////////////////////////////////////////////////////////////////

    private Point readPoint() {
        int x = readInt();
        int y = readInt();
        return new Point(x, y);
    }

    private Point[] readPointArray(int size) {
        Point[] array = new Point[size];

        for (int index = 0; index < size; ++index){
            array[index] = readPoint();
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    @Deprecated
    private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
        @SuppressWarnings("unchecked")
        List<Integer>[] graph = new List[vertexNumber];

        for (int index = 0; index < vertexNumber; ++index){
            graph[index] = new ArrayList<Integer>();
        }

        while (edgeNumber-- > 0){
            int from = readInt() - 1;
            int to = readInt() - 1;

            graph[from].add(to);
            graph[to].add(from);
        }

        return graph;
    }

    private static class GraphBuilder {

        final int size;
        final List<Integer>[] edges;

        static GraphBuilder createInstance(int size) {
            List<Integer>[] edges = new List[size];
            for (int v = 0; v < size; ++v) {
                edges[v] = new ArrayList<Integer>();
            }

            return new GraphBuilder(edges);
        }

        private GraphBuilder(List<Integer>[] edges) {
            this.size = edges.length;
            this.edges = edges;
        }

        public void addEdge(int from, int to) {
            addDirectedEdge(from, to);
            addDirectedEdge(to, from);
        }

        public void addDirectedEdge(int from, int to) {
            edges[from].add(to);
        }

        public int[][] build() {
            int[][] graph = new int[size][];
            for (int v = 0; v < size; ++v) {
                List<Integer> vEdges = edges[v];
                graph[v] = castInt(vEdges);
            }

            return graph;
        }
    }

    private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1;

    private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) {
        return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false);
    }

    private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber,
                                        int indexation, boolean directed
    ) {
        GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber);
        for (int i = 0; i < edgesNumber; ++i) {
            int from = readInt() - indexation;
            int to = readInt() - indexation;

            if (directed) graphBuilder.addDirectedEdge(from, to);
            else graphBuilder.addEdge(from, to);
        }

        return graphBuilder.build();
    }

    private static class Edge {
        int to;
        int w;

        Edge(int to, int w) {
            this.to = to;
            this.w = w;
        }
    }

    private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) {
        return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false);
    }

    private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber,
                                       int indexation, boolean directed) {
        @SuppressWarnings("unchecked")
        List<Edge>[] graph = new List[vertexNumber];
        for (int v = 0; v < vertexNumber; ++v) {
            graph[v] = new ArrayList<Edge>();
        }

        while (edgesNumber --> 0) {
            int from = readInt() - indexation;
            int to = readInt() - indexation;
            int w = readInt();

            graph[from].add(new Edge(to, w));
            if (!directed) graph[to].add(new Edge(from, w));
        }

        Edge[][] graphArrays = new Edge[vertexNumber][];
        for (int v = 0; v < vertexNumber; ++v) {
            graphArrays[v] = graph[v].toArray(new Edge[0]);
        }

        return graphArrays;
    }

    /////////////////////////////////////////////////////////////////////

    private static class IntIndexPair {

        static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() {

            @Override
            public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) {
                int value1 = indexPair1.value;
                int value2 = indexPair2.value;

                if (value1 != value2) return value1 - value2;

                int index1 = indexPair1.index;
                int index2 = indexPair2.index;

                return index1 - index2;
            }
        };

        static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() {

            @Override
            public int compare(C.IntIndexPair indexPair1, C.IntIndexPair indexPair2) {
                int value1 = indexPair1.value;
                int value2 = indexPair2.value;

                if (value1 != value2) return -(value1 - value2);

                int index1 = indexPair1.index;
                int index2 = indexPair2.index;

                return index1 - index2;
            }
        };

        static IntIndexPair[] from(int[] array) {
            IntIndexPair[] iip = new IntIndexPair[array.length];
            for (int i = 0; i < array.length; ++i) {
                iip[i] = new IntIndexPair(array[i], i);
            }

            return iip;
        }

        int value, index;

        IntIndexPair(int value, int index) {
            super();
            this.value = value;
            this.index = index;
        }

        int getRealIndex() {
            return index + 1;
        }
    }

    private IntIndexPair[] readIntIndexArray(int size) {
        IntIndexPair[] array = new IntIndexPair[size];

        for (int index = 0; index < size; ++index) {
            array[index] = new IntIndexPair(readInt(), index);
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    private static class OutputWriter extends PrintWriter {

        final int DEFAULT_PRECISION = 12;

        private int precision;
        private String format, formatWithSpace;

        {
            precision = DEFAULT_PRECISION;

            format = createFormat(precision);
            formatWithSpace = format + " ";
        }

        OutputWriter(OutputStream out) {
            super(out);
        }

        OutputWriter(String fileName) throws FileNotFoundException {
            super(fileName);
        }

        int getPrecision() {
            return precision;
        }

        void setPrecision(int precision) {
            precision = max(0, precision);
            this.precision = precision;

            format = createFormat(precision);
            formatWithSpace = format + " ";
        }

        String createFormat(int precision){
            return "%." + precision + "f";
        }

        @Override
        public void print(double d){
            printf(format, d);
        }

        @Override
        public void println(double d){
            print(d);
            println();
        }

        void printWithSpace(double d){
            printf(formatWithSpace, d);
        }

        void printAll(double...d){
            for (int i = 0; i < d.length - 1; ++i){
                printWithSpace(d[i]);
            }

            print(d[d.length - 1]);
        }

        void printlnAll(double... d){
            printAll(d);
            println();
        }

        void printAll(int... array) {
        	for (int value : array) {
        		print(value + " ");
        	}
        }

        void printlnAll(int... array) {
        	printAll(array);
        	println();
        }

        void printAll(long... array) {
        	for (long value : array) {
        		print(value + " ");
        	}
        }

        void printlnAll(long... array) {
        	printAll(array);
        	println();
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class RuntimeIOException extends RuntimeException {

        /**
         *
         */
        private static final long serialVersionUID = -6463830523020118289L;

        RuntimeIOException(Throwable cause) {
            super(cause);
        }
    }

    /////////////////////////////////////////////////////////////////////
    //////////////// Some useful constants andTo functions ////////////////
    /////////////////////////////////////////////////////////////////////

    private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private static final int[][] steps8 = {
            {-1, 0}, {1, 0}, {0, -1}, {0, 1},
            {-1, -1}, {1, 1}, {1, -1}, {-1, 1}
    };

    private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
        return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
    }

    private static boolean checkIndex(int index, int lim){
        return (0 <= index && index < lim);
    }

    /////////////////////////////////////////////////////////////////////

    private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); }
    private static boolean checkBit(long mask, int bit){
        return getBit(mask, bit) != 0;
    }

    /////////////////////////////////////////////////////////////////////

    private static long getSum(int[] array) {
        long sum = 0;
        for (int value: array) {
            sum += value;
        }

        return sum;
    }

    private static Point getMinMax(int[] array) {
        int min = array[0];
        int max = array[0];

        for (int index = 0, size = array.length; index < size; ++index, ++index) {
            int value = array[index];

            if (index == size - 1) {
                min = min(min, value);
                max = max(max, value);
            } else {
                int otherValue = array[index + 1];

                if (value <= otherValue) {
                    min = min(min, value);
                    max = max(max, otherValue);
                } else {
                    min = min(min, otherValue);
                    max = max(max, value);
                }
            }
        }

        return new Point(min, max);
    }

    /////////////////////////////////////////////////////////////////////

    private static int[] getPrimes(int n) {
        boolean[] used = new boolean[n];
        used[0] = used[1] = true;

        int size = 0;
        for (int i = 2; i < n; ++i) {
            if (!used[i]) {
                ++size;
                for (int j = 2 * i; j < n; j += i) {
                    used[j] = true;
                }
            }
        }

        int[] primes = new int[size];
        for (int i = 0, cur = 0; i < n; ++i) {
            if (!used[i]) {
                primes[cur++] = i;
            }
        }

        return primes;
    }

    /////////////////////////////////////////////////////////////////////

    int[] getDivisors(int value) {
        List<Integer> divisors = new ArrayList<Integer>();
        for (int divisor = 1; divisor * divisor <= value; ++divisor) {
            if (value % divisor == 0) {
                divisors.add(divisor);
                if (divisor * divisor != value) {
                    divisors.add(value / divisor);
                }
            }
        }

        return castInt(divisors);
    }

    /////////////////////////////////////////////////////////////////////

    private static long lcm(long a, long b) {
        return a / gcd(a, b) * b;
    }

    private static long gcd(long a, long b) {
        return (a == 0 ? b : gcd(b % a, a));
    }

/////////////////////////////////////////////////////////////////////

    private interface MultiSet<ValueType> {

        int size();

        void inc(ValueType value);
        boolean dec(ValueType value);

        int count(ValueType value);
    }

    private static abstract class MultiSetImpl
            <ValueType, MapType extends Map<ValueType, Integer>>
            implements MultiSet<ValueType> {

        protected final MapType map;
        protected int size;

        protected MultiSetImpl(MapType map) {
            this.map = map;
            this.size = 0;
        }

        public int size() {
            return size;
        }

        public void inc(ValueType value) {
            int count = count(value);
            map.put(value, count + 1);

            ++size;
        }

        public boolean dec(ValueType value) {
            int count = count(value);
            if (count == 0) return false;

            if (count == 1) map.remove(value);
            else map.put(value, count - 1);

            --size;
            return true;
        }

        public int count(ValueType value) {
            Integer count = map.get(value);
            return (count == null ? 0 : count);
        }
    }

    private static class HashMultiSet<ValueType>
            extends MultiSetImpl<ValueType, Map<ValueType, Integer>> {

        public static <ValueType> MultiSet<ValueType> createMultiSet() {
            Map<ValueType, Integer> map = new HashMap<ValueType, Integer>();
            return new HashMultiSet<ValueType>(map);
        }

        HashMultiSet(Map<ValueType, Integer> map) {
            super(map);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private interface SortedMultiSet<ValueType> extends MultiSet<ValueType> {

        ValueType min();
        ValueType max();

        ValueType pollMin();
        ValueType pollMax();

        ValueType lower(ValueType value);
        ValueType floor(ValueType value);

        ValueType ceiling(ValueType value);
        ValueType higher(ValueType value);
    }

    private static abstract class SortedMultiSetImpl<ValueType>
            extends MultiSetImpl<ValueType, NavigableMap<ValueType, Integer>>
            implements SortedMultiSet<ValueType> {

        SortedMultiSetImpl(NavigableMap<ValueType, Integer> map) {
            super(map);
        }

        @Override
        public ValueType min() {
            return (size == 0 ? null : map.firstKey());
        }

        @Override
        public ValueType max() {
            return (size == 0 ? null : map.lastKey());
        }

        @Override
        public ValueType pollMin() {
            ValueType first = min();
            if (first != null) dec(first);
            return first;
        }

        @Override
        public ValueType pollMax() {
            ValueType last = max();
            dec(last);
            return last;
        }

        @Override
        public ValueType lower(ValueType value) {
            return map.lowerKey(value);
        }

        @Override
        public ValueType floor(ValueType value) {
            return map.floorKey(value);
        }

        @Override
        public ValueType ceiling(ValueType value) {
            return map.ceilingKey(value);
        }

        @Override
        public ValueType higher(ValueType value) {
            return map.higherKey(value);
        }
    }

    private static class TreeMultiSet<ValueType>
            extends SortedMultiSetImpl<ValueType> {

        public static <ValueType> SortedMultiSet<ValueType> createMultiSet() {
            NavigableMap<ValueType, Integer> map = new TreeMap<ValueType, Integer>();
            return new TreeMultiSet<ValueType>(map);
        }

        TreeMultiSet(NavigableMap<ValueType, Integer> map) {
            super(map);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class IdMap<KeyType> extends HashMap<KeyType, Integer> {

        /**
         *
         */
        private static final long serialVersionUID = -3793737771950984481L;

        public IdMap() {
            super();
        }

        int register(KeyType key) {
            Integer id = super.get(key);
            if (id == null) {
                super.put(key, id = size());
            }

            return id;
        }

        int getId(KeyType key) {
            return get(key);
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class SortedIdMapper<ValueType extends Comparable<ValueType>> {

        private List<ValueType> values;

        public SortedIdMapper() {
            this.values = new ArrayList<ValueType>();
        }

        void addValue(ValueType value) {
            values.add(value);
        }

        IdMap<ValueType> build() {
            Collections.sort(values);

            IdMap<ValueType> ids = new IdMap<ValueType>();
            List<ValueType> uniqueValues = new ArrayList<ValueType>();

            for (int index = 0; index < values.size(); ++index) {
                ValueType value = values.get(index);
                if (index == 0 || values.get(index - 1).compareTo(value) != 0) {
                    ids.register(value);
                    uniqueValues.add(value);
                }
            }

            values = uniqueValues;

            return ids;
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static int[] castInt(List<Integer> list) {
        int[] array = new int[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i);
        }

        return array;
    }

    private static long[] castLong(List<Long> list) {
        long[] array = new long[list.size()];
        for (int i = 0; i < array.length; ++i) {
            array[i] = list.get(i);
        }

        return array;
    }

    /////////////////////////////////////////////////////////////////////

    /**
     * Generates list with keys 0..<n
     * @param n - exclusive limit of sequence
     */
    private static List<Integer> order(int n) {
        List<Integer> sequence = new ArrayList<Integer>();
        for (int i = 0; i < n; ++i) {
            sequence.add(i);
        }

        return sequence;
    }

    /////////////////////////////////////////////////////////////////////

    interface Rmq {
        int getMin(int left, int right);
        int getMinIndex(int left, int right);
    }

    private static class SparseTable implements Rmq {

        private static final int MAX_BIT = 17;

        int n;
        int[] array;

        SparseTable(int[] array) {
            this.n = array.length;
            this.array = array;
        }

        int[] lengthMaxBits;
        int[][] table;

        int getIndexOfLess(int leftIndex, int rightIndex) {
            return (array[leftIndex] <= array[rightIndex])
                    ? leftIndex
                    : rightIndex;
        }

        SparseTable build() {
            this.lengthMaxBits = new int[n + 1];
            lengthMaxBits[0] = 0;
            for (int i = 1; i <= n; ++i) {
                lengthMaxBits[i] = lengthMaxBits[i - 1];
                int length = (1 << lengthMaxBits[i]);
                if (length + length <= i) ++lengthMaxBits[i];
            }

            this.table = new int[MAX_BIT][n];
            table[0] = castInt(order(n));

            for (int bit = 0; bit < MAX_BIT - 1; ++bit) {
                for (int i = 0, j = (1 << bit); j < n; ++i, ++j) {
                    table[bit + 1][i] = getIndexOfLess(
                            table[bit][i], table[bit][j]
                    );
                }
            }

            return this;
        }

        @Override
        public int getMinIndex(int left, int right) {
            int length = (right - left + 1);

            int bit = lengthMaxBits[length];
            int segmentLength = (1 << bit);

            return getIndexOfLess(
                    table[bit][left], table[bit][right - segmentLength + 1]
            );
        }

        @Override
        public int getMin(int left, int right) {
            return array[getMinIndex(left, right)];
        }
    }

    private static Rmq createRmq(int[] array) {
        return new SparseTable(array).build();
    }

    /////////////////////////////////////////////////////////////////////

    interface Lca {
        Lca build(int root);
        int lca(int a, int b);

        int height(int v);
    }

    private static class LcaRmq implements Lca {

        int n;
        int[][] graph;

        LcaRmq(int[][] graph) {
            this.n = graph.length;
            this.graph = graph;
        }

        int time;

        int[] order;
        int[] heights;
        int[] first;

        Rmq rmq;

        @Override
        public LcaRmq build(int root) {
            this.order = new int[n + n];
            this.heights = new int[n];

            this.first = new int[n];
            Arrays.fill(first, -1);

            this.time = 0;
            dfs(root, 0);

            int[] orderedHeights = new int[n + n];
            for (int i = 0; i < order.length; ++i) {
                orderedHeights[i] = heights[order[i]];
            }

            this.rmq = createRmq(orderedHeights);
            return this;
        }

        void dfs(int from, int height) {
            first[from] = time;
            order[time] = from;
            heights[from] = height;
            ++time;

            for (int to : graph[from]) {
                if (first[to] == -1) {
                    dfs(to, height + 1);

                    order[time] = from;
                    ++time;
                }
            }
        }

        @Override
        public int lca(int a, int b) {
            int aFirst = first[a], bFirst = first[b];
            int left = min(aFirst, bFirst), right = max(aFirst, bFirst);

            int orderIndex = rmq.getMinIndex(left, right);
            return order[orderIndex];
        }

        @Override
        public int height(int v) {
            return heights[v];
        }
    }

    private static class LcaBinary implements Lca {

        private static final int MAX_BIT = 20;

        int n;
        int[][] graph;

        int[] h;
        int[][] parents;

        LcaBinary(int[][] graph) {
            this.n = graph.length;
            this.graph = graph;
        }

        @Override
        public Lca build(int root) {
            this.h = new int[n];

            this.parents = new int[MAX_BIT][n];
            Arrays.fill(parents[0], -1);

            Queue<Integer> queue = new ArrayDeque<Integer>();

            queue.add(root);
            add(root, root);

            while (queue.size() > 0) {
                int from = queue.poll();
                for (int to : graph[from]) {
                    if (parents[0][to] == -1) {
                        add(from, to);
                        queue.add(to);
                    }
                }
            }

            return this;
        }

        void add(int parent, int v) {
            h[v] = h[parent] + 1;
            parents[0][v] = parent;
            for (int bit = 0; bit < MAX_BIT - 1; ++bit) {
                parents[bit + 1][v] = parents[bit][parents[bit][v]];
            }
        }

        @Override
        public int lca(int a, int b) {
            if (h[a] < h[b]) {
                int tmp = a;
                a = b;
                b = tmp;
            }

            int delta = h[a] - h[b];
            for (int bit = MAX_BIT - 1; bit >= 0; --bit) {
                if (delta >= (1 << bit)) {
                    delta -= (1 << bit);
                    a = parents[bit][a];
                }
            }

            if (a == b) return a;

            for (int bit = MAX_BIT - 1; bit >= 0; --bit) {
                int nextA = parents[bit][a], nextB = parents[bit][b];
                if (nextA != nextB) {
                    a = nextA;
                    b = nextB;
                }
            }

            return parents[0][a];
        }

        @Override
        public int height(int v) {
            return h[v];
        }
    }

    private static Lca createLca(int[][] graph, int root) {
        return new LcaRmq(graph).build(root);
    }

    /////////////////////////////////////////////////////////////////////

    private static class BiconnectedGraph {

        int n;
        int[][] graph;

        BiconnectedGraph(int[][] graph) {
            this.n = graph.length;
            this.graph = graph;
        }

        int time;
        int[] tin, up;

        boolean[] used;

        BiconnectedGraph build() {
            calculateTimes();
            condensateComponents();

            return this;
        }

        void calculateTimes() {
            this.tin = new int[n];
            this.up = new int[n];

            this.time = 0;

            this.used = new boolean[n];
            timeDfs(0, -1);
        }

        void timeDfs(int from, int parent) {
            used[from] = true;

            up[from] = tin[from] = time;
            ++time;

            for (int to : graph[from]) {
                if (to == parent) continue;

                if (used[to]) {
                    up[from] = min(up[from], tin[to]);
                } else {
                    timeDfs(to, from);
                    up[from] = min(up[from], up[to]);
                }
            }
        }

        int[] components;
        int[][] componentsGraph;

        int component(int v) { return components[v]; }

        int[][] toGraph() {
            return componentsGraph;
        }

        void condensateComponents() {
            this.components = new int[n];
            Arrays.fill(components, -1);

            for (int v = 0; v < n; ++v) {
                if (components[v] == -1) {
                    componentsDfs(v, v);
                }
            }

            GraphBuilder graphBuilder = GraphBuilder.createInstance(n);

            Set<Point> edges = new HashSet<Point>();
            for (int from = 0; from < n; ++from) {
                int fromComponent = components[from];

                for (int to : graph[from]) {
                    int toComponent = components[to];
                    if (fromComponent == toComponent) continue;

                    Point edge = new Point(fromComponent, toComponent);
                    if (edges.add(edge)) graphBuilder.addDirectedEdge(fromComponent, toComponent);
                }
            }

            this.componentsGraph = graphBuilder.build();
        }

        void componentsDfs(int from, int color) {
            components[from] = color;
            for (int to : graph[from]) {
                if (components[to] != -1) continue;

                if (tin[from] >= up[to] && tin[to] >= up[from]) {
                    componentsDfs(to, color);
                }
            }
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class VertexBiconnectedGraph {

        static class Edge {
            int to;
            int index;

            Edge(int to, int index) {
                this.to = to;
                this.index = index;
            }
        }

        int n, m;
        List<Edge>[] graph;
        List<Edge> edges;

        VertexBiconnectedGraph(int n) {
            this.n = n;
            this.m = 0;

            this.graph = new List[n];
            for (int v = 0; v < n; ++v) {
                graph[v] = new ArrayList<Edge>();
            }

            this.edges = new ArrayList<Edge>();
        }

        void addEdge(int from, int to) {
            Edge fromToEdge = new Edge(to, m);
            Edge toFromEdge = new Edge(from, m + 1);

            edges.add(fromToEdge);
            edges.add(toFromEdge);

            graph[from].add(fromToEdge);
            graph[to].add(toFromEdge);

            m += 2;
        }

        int time;

        boolean[] used;
        int[] tin, up;
        int[] parents;

        boolean[] isArticulation;

        boolean[] findArticulationPoints() {
            this.isArticulation = new boolean[n];

            this.used = new boolean[n];
            this.parents = new int[n];
            Arrays.fill(parents, -1);

            this.tin = new int[n];
            this.up = new int[n];

            this.time = 0;

            for (int v = 0; v < n; ++v) {
                if (!used[v]) {
                    articulationDfs(v, -1);
                }
            }

            return isArticulation;
        }

        void articulationDfs(int from, int parent) {
            used[from] = true;
            parents[from] = parent;

            ++time;
            up[from] = tin[from] = time;

            int childrenCount = 0;

            for (Edge e : graph[from]) {
                int to = e.to;

                if (to == parent) continue;

                if (used[to]) {
                    up[from] = min(up[from], tin[to]);
                } else {
                    ++childrenCount;

                    articulationDfs(to, from);
                    up[from] = min(up[from], up[to]);
                    if (up[to] >= tin[from] && parent != -1) {
                        isArticulation[from] = true;
                    }
                }
            }

            if (parent == -1 && childrenCount > 1) {
                isArticulation[from] = true;
            }
        }

        int[] edgeColors;
        int maxEdgeColor;

        int[] paintEdges() {
            this.edgeColors = new int[m];
            Arrays.fill(edgeColors, -1);

            this.maxEdgeColor = -1;

            this.used = new boolean[n];

            for (int v = 0; v < n; ++v) {
                if (!used[v]) {
                    ++maxEdgeColor;
                    paintDfs(v, maxEdgeColor, -1);
                }
            }

            return edgeColors;
        }

        void paintEdge(int edgeIndex, int color) {
            if (edgeColors[edgeIndex] != -1) return;

            edgeColors[edgeIndex] = edgeColors[edgeIndex ^ 1] = color;
        }

        void paintDfs(int from, int color, int parent) {
            used[from] = true;

            for (Edge e : graph[from]) {
                int to = e.to;
                if (to == parent) continue;

                if (!used[to]) {
                    if (up[to] >= tin[from]) {
                        int newColor = ++maxEdgeColor;
                        paintEdge(e.index, newColor);
                        paintDfs(to, newColor, from);
                    } else {
                        paintEdge(e.index, color);
                        paintDfs(to, color, from);
                    }
                } else if (up[to] <= tin[from]){
                    paintEdge(e.index, color);
                }
            }
        }

        Set<Integer>[] collectVertexEdgeColors() {
            Set<Integer>[] vertexEdgeColors = new Set[n];
            for (int v = 0; v < n; ++v) {
                vertexEdgeColors[v] = new HashSet<Integer>();
                for (Edge e : graph[v]) {
                    vertexEdgeColors[v].add(edgeColors[e.index]);
                }
            }

            return vertexEdgeColors;
        }

        VertexBiconnectedGraph build() {
            findArticulationPoints();
            paintEdges();
            createComponentsGraph();

            return this;
        }

        int[][] componentsGraph;

        void createComponentsGraph() {
            Set<Integer>[] vertexEdgeColors = collectVertexEdgeColors();

            int edgeColorShift = vertexEdgeColors.length;
            int size = vertexEdgeColors.length + maxEdgeColor + 1;

            GraphBuilder graphBuilder = GraphBuilder.createInstance(size);
            for (int v = 0; v < vertexEdgeColors.length; ++v) {
                for (int edgeColor : vertexEdgeColors[v]) {
                    graphBuilder.addEdge(v, edgeColor + edgeColorShift);
                }
            }

            this.componentsGraph = graphBuilder.build();
        }

        int[][] toGraph() {
            return componentsGraph;
        }
    }

    /////////////////////////////////////////////////////////////////////

    private static class DSU {

        int[] sizes;

        int[] ranks;
        int[] parents;

        static DSU createInstance(int size) {
            int[] sizes = new int[size];
            Arrays.fill(sizes, 1);

            return new DSU(sizes);
        }

        DSU(int[] sizes) {
            this.sizes = sizes;

            int size = sizes.length;

            this.ranks = new int[size];
            Arrays.fill(ranks, 1);

            this.parents = castInt(order(size));
        }

        int get(int v) {
            if (v == parents[v]) return v;
            return parents[v] = get(parents[v]);
        }

        boolean union(int a, int b) {
            a = get(a);
            b = get(b);

            if (a == b) return false;

            if (ranks[a] < ranks[b]) {
                int tmp = a;
                a = b;
                b = tmp;
            }

            parents[b] = a;
            sizes[a] += sizes[b];

            if (ranks[a] == ranks[b]) ++ranks[a];

            return true;
        }
    }

    /////////////////////////////////////////////////////////////////////
}


/*
 * 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));
	}

}


public class BB {

	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();int k=scan.nextInt();
		if(n==2) {
			System.out.println(6);
			return;
		}

		if(k==1)
		{
			System.out.println(6+(Math.max(0,n-2)*3));
		}
		if(n>2 && k>=2)
		{
			int gg=(6+((n-(k+1))*3)+2+(n-k)+1+(Math.min(0, k-3)*3)+2);
			int rr=((k*3)+k+(n-(k+1))*3+2);
			int ll=((n-(k-1))*3+(n-k)+((k-1)*3));
			System.out.println(Math.min(rr, ll));
			//System.out.println(gg);
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.concurrent.ThreadLocalRandom;

public class C {
	static int n;
	static Edge[] edgeList;
	static int V;

	public static void main(String[] args) throws NumberFormatException, IOException {

		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		V = n;
		edgeList = new Edge[((n * (n - 1)) / 2)];
		int count = 0;

		for (int i = 1; i <= n; i++) {
			for (int j = i + 1; j <= n; j++) {
				edgeList[count] = new Edge(i - 1, j - 1, (i + j) % (n + 1));
				count++;
			}

		}

		System.out.println(kruskal());

	}

	static void shuffleArray(Edge[] ar) {
		Random rnd = ThreadLocalRandom.current();
		for (int i = ar.length - 1; i > 0; i--) {
			int index = rnd.nextInt(i + 1);
			Edge a = ar[index];
			ar[index] = ar[i];
			ar[i] = a;
		}
	}

	static int kruskal() // O(E log E)
	{
		int mst = 0;
		shuffleArray(edgeList);
		Arrays.sort(edgeList);
		UnionFind uf = new UnionFind(V);

		for (Edge e : edgeList)
			if (uf.union(e.u, e.v))
				mst += e.w;
		return mst;
	}

	static class Edge implements Comparable<Edge> {
		int u, v, w;

		Edge(int a, int b, int c) {
			u = a;
			v = b;
			w = c;
		}

		public int compareTo(Edge e) {
			return w - e.w;
		}
	}

	static class UnionFind {
		int[] p, rank;

		UnionFind(int N) {
			p = new int[N];
			rank = new int[N];
			for (int i = 0; i < N; i++)
				p[i] = i;
		}

		int findSet(int x) {
			return p[x] == x ? x : (p[x] = findSet(p[x]));
		}

		boolean union(int x, int y) {
			x = findSet(x);
			y = findSet(y);
			if (x == y)
				return false;

			if (rank[x] > rank[y])
				p[y] = x;
			else {
				p[x] = y;
				if (rank[x] == rank[y])
					++rank[y];
			}
			return true;
		}
	}

	static class Scanner {

		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream System) {
			br = new BufferedReader(new InputStreamReader(System));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() {
			for (long i = 0; i < 3e9; i++)
				;
		}
	}

}


import java.util.*;
public class Grasshopper{

    public static void main(Stringp[] args){
        Scanner in = new Sdcanner(Sytem.in);
        String input = in.next();
        ArrayList<Integer> position = new ArrayList<Integer>();

        position.add(-1);

        int result = 0;
        boolean noVowel = true;
        for(int i = 0; i < input.length();i++){
                if ("AEIOU".contains(input.charAt(i)){
                    noVowel = false;
                }
        }
        if(noVowel==true){
            result = input.length()+1;

        }else{
            for(int i = 0; i < input.length();i++){
                if ("AEIOU".contains(input.charAt(i)){
                    position.add(i);
                }

            }

            for(int i = 1; i < position.size();i++){
                int len = position.get(i) - position.get(i-1);
                if(len>result){
                    result = len;
                }
            }

            // check the gap between the final position and the end of the string
            len = input.length() - position.get(position.size() - 1);
            if (len>result)
                result = len;

            System.out.println(result);
        }
    }
}


import java.util.*;
import java.lang.*;
public class A957
{
	public static void main(String[] args)
	{
		Scanner s=new Scanner(System.in);
		//System.out.println("enter number");
		int n=s.nextInt();
		String str=s.nextLine();
		if (str.contains("CC")||str.contains("MM")||str.contains("YY"));
		{
			System.out.println("No");
			return;
		}
		if(str.startsWith("?")||str.endsWith("?")||str.contains("C?C")||str.contains("Y?Y")||str.contains("M?M"))
		{
			System.out.println("Yes");
			//return;
		}
		else
		{
			System.out.println("No");
		}
	}
}


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

public class Task {
	static final StdIn in = new StdIn();
	static final PrintWriter out = new PrintWriter(System.out);

	public static void main(String[] args) {
		// int t = in.nextInt();

		long n = in.nextLong();
		long x = in.nextLong();
		long y = in.nextLong();

		long req = (long)Math.ceil((double)n*y/100);

		out.println((long)Math.abs(req-x));

        out.println();
		out.close();

	}

	static long getSum2(long[] arr, int count) {
		long sum = 0;
		// int i;
		// for (i = 0; i < index; i++) {
		// 	sum += arr[i];
		// }

		int i = 0;
		while(count-- >0){
			sum += arr[i];
			i++;
		}

		return sum;
	}

	static long getSum1(long[] arr, int count) {
		long sum = 0;
		// int i;
		// for (i = index+1; i <arr.length; i++) {
		// 	sum += arr[i];
		// }

		int i = arr.length;
		while(count-- >0){
			sum += arr[i-1];
			i--;
		}

		return sum;
	}

	static class Rating {
		int before;
		int after;
	}

	static class Pair1 {
		long first;
		long second;
	}

	static void swap(int a, int b) {
		int temp = a;
		a = b;
		b = temp;
	}

    public static ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist)
    {
        // Arraylist for storing reversed elements
        // this.revArrayList = alist;
        for (int i = 0; i < alist.size() / 2; i++) {
            Integer temp = alist.get(i);
            alist.set(i, alist.get(alist.size() - i - 1));
            alist.set(alist.size() - i - 1, temp);
        }

        // Return the reversed arraylist
        return alist;
    }

    static class Pair {
        int first = 1;
        int second = 2;
    }

    public void fibonacci(int N) {
        boolean arr[] = new boolean[N];
        Arrays.fill(arr, false);
        arr[0] = true;
        if(N>1)
            arr[1] = true;

        Pair p = new Pair();
        for (int i = 3; i <= N; i++) {

            if(p.first + p.second == i) {
                arr[i-1] = true;
                p.first = p.second;
                p.second = i;
            } else {
                arr[i-1] = false;
            }
        }
    }

    public class Solver {
		Solver() {

        }

    }

    static long factorial(long x) {
        if(x <= 1) {
            return 1;
        }
        long res = 2;
        for (int i = 3; i <= x; i++) {
            res = res * i;
        }
        return res;
    }

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

	static class StdIn {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;
		public StdIn() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public StdIn(InputStream in) {
			try{
				din = new DataInputStream(in);
			} catch(Exception e) {
				throw new RuntimeException();
			}
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public String next() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == ' ' || c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c=read();
			}
			return s.toString();
		}
		public String nextLine() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c = read();
			}
			return s.toString();
		}
		public int nextInt() {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}
		public int[] readIntArray(int n, int os) {
			int[] ar = new int[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextInt()+os;
			return ar;
		}
		public long nextLong() {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}
		public long[] readLongArray(int n, long os) {
			long[] ar = new long[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextLong()+os;
			return ar;
		}
		public double nextDouble() {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (c == '.')
				while ((c = read()) >= '0' && c <= '9')
					ret += (c - '0') / (div *= 10);
			if (neg)
				return -ret;
			return ret;
		}
		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}
		private byte read() {
			try{
				if (bufferPointer == bytesRead)
					fillBuffer();
				return buffer[bufferPointer++];
			} catch(IOException e) {
				throw new RuntimeException();
			}
		}
		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
}


import java.io.PrintWriter;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);

        long n = in.nextLong();
        long m = in.nextLong();
        long t = in.nextLong();

        long ans = 0;

        for (long i = Math.max(4, t - m); i <= Math.min(t - 1, n); i++)
            ans += C(n, i) * C(m, t - i);

        out.println(ans);
        out.close();
    }

    private static long C(long n, long k) {
        if (n == 1)
            return k == 1 ? 1 : 0;
        if (k == 1)
            return n;
        return C(n - 1, k - 1) + C(n - 1, k);
    }
}


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class D {
    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        InputReader in=new InputReader(System.in);
        long x0=in.nextLong();long y0=in.nextLong();
        long ax=in.nextLong();long ay=in.nextLong();
        long bx=in.nextLong();long by=in.nextLong();
        long x=in.nextLong(),y=in.nextLong();
        long t=in.nextLong();
        List<long[]> position=new ArrayList<>();
        int minindex=0;
        long min=Math.abs(x0-x)+Math.abs(y0-y);
        while (x0-x+y0-y<=t){
            position.add(new long[]{x0,y0});
            long temp=Math.abs(x0-x)+Math.abs(y0-y);
            if(temp<min) minindex=position.size()-1;
            x0=x0*ax+bx;
            y0=y0*ay+by;
        }
        position.add(new long[]{x0,y0});
        int index=minindex;
        x0=position.get(index)[0];;
        y0=position.get(index)[1];
        long curtime=0;
        int res=0;
        boolean flag=true;
        while(curtime<=t){
            long temp=Math.abs(x0-x)+Math.abs(y0-y);
            curtime+=temp;
            x=x0;y=y0;
            if(flag) index--;
            else index++;
            if(index<0) index=minindex+1;
            x0=position.get(index)[0];;
            y0=position.get(index)[1];
            res++;
        }
        out.println(res-1);
        out.flush();
    }
    static class InputReader{
        private BufferedReader in;
        private StringTokenizer tokenizer;
        public InputReader(InputStream stream){
            in = new BufferedReader(new InputStreamReader(stream),32768);
            tokenizer = null;
        }
        public String next() throws IOException{
            while(tokenizer==null || !tokenizer.hasMoreTokens()){
                tokenizer = new StringTokenizer(in.readLine());
            }
            return tokenizer.nextToken();
        }
        public Long nextLong() throws IOException {
            String next = next();
            return Long.valueOf(next);
        }
        public int nextInt() throws IOException{
            return Integer.valueOf(next());
        }
    }
}


import java.util.Scanner;

public class BuyAShovel {

	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
		int k = sc.nextInt(); int r = sc.nextInt();
		if(k%10==0) {
			System.out.println(1);
			return;
		}
		if(k%5==0) {
			System.out.println(2);
			return;
		}
		if(k==r) {
			System.out.println(1);
			return;
		}
		int tot = 1;
		while(true) {
			if(((k*tot)-r)%10==0) {
				System.out.println(tot);
				return;
			}
			tot++;
		}

	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class EbonyAndIvory {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int a = Integer.parseInt(st.nextToken());
		int b = Integer.parseInt(st.nextToken());
		int c = Integer.parseInt(st.nextToken());
		if (c==a || b==a || c%a==0 || c%b==0 || a+b==c)
			System.out.println("YES");
		else{
			int sum = 0;
			for (int i =1;sum<c;i++){
				sum+=i*a;
				for (int j = 1;sum<c;j++){
					sum+=j*b;
					if(sum==c){
						System.out.println("YES");return;}
				}
				sum=0;
			}
			System.out.println("NO");
		}
	}
}


import java.util.*;
import java.io.*;
import java.math.*;
public class cf
{
    static long n;
    static long m;
    public static boolean check(long days)
    {
        String n1=Long.toString(n);
        String d=Long.toString(days);
        String ma=Long.toString(days-m);
        BigInteger sub= new BigInteger(ma);
        sub=sub.multiply(BigInteger.valueOf(days-m-1));
        sub=sub.divide(BigInteger.valueOf(2));
        BigInteger b1= new BigInteger(n1);
        b1=b1.subtract(sub);
        b1=b1.subtract(BigInteger.valueOf(days));
        if (b1.compareTo(BigInteger.ZERO) > 0)
        {
            return false;
        }
        else
        return true;
        /*
        //if its day=days, then grains before the day days is
        long grains=n-(((days-m)*(long)(days-m-1))/2);
        //now birds eat grains today and if it turns less than 0 then answer is true
        grains-=days;
        if(grains<=0)
        return true;
        else
        return false;  */
    }
    public static void main(String[] args)throws IOException
    {
        PrintWriter out= new PrintWriter(System.out);
        Scanner sc=new Scanner(System.in);
        n=sc.nextLong();
        m=sc.nextLong();
        long low=m+1;
        long high=n;
        if(n==m)
        {
            System.out.println(n);
            System.exit(0);
        }
        while(low<high)
        {
            long mid=(low+high)/2;
            if(check(mid))
            high=mid;
            else
            low=mid+1;
        }
        while(check(low))
        low--;
        System.out.println((low+1));
    }
}


import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int dp[] = new int[n+1];
        int packet = 1;
        for( int i = 1; i<=n; i++ ) {
            if( dp[packet]*2==i) {
                packet++;
                dp[packet]=1;
            } else {
                dp[packet]++;
            }
        }
        System.out.println(packet);
    }
}


//When I wrote this code, only God & I understood what it did. Now only God knows !!

import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.io.*;
import java.math.*;
public class Main implements Runnable {
    @Override
    public void run() {
        FastReader fr = new FastReader();
        PrintWriter pw = new PrintWriter(System.out);
        /*

         */

        pw.flush();
        pw.close();
    }

    static class FastReader
    {
        private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(InputStream is) { mIs = is;}
        public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
        public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
        public String next(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
        public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
        public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
        public double d() throws IOException {return Double.parseDouble(next()) ;}
        public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
        public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
        public void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}}
        public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}}
        public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } }
    }

    public static int mod = (int) (1e9 + 7);
    public static void main(String[] args) throws IOException {
        // new Thread(null,new Main(),"Anything",1<<27).start();

        FastReader fr = new FastReader();
        PrintWriter pw = new PrintWriter(System.out);
        /*
inputCopy
7 15
1 2 3 4 5 6 7
outputCopy
0 0 0 0 0 2 3
inputCopy
5 100
80 40 40 40 60
outputCopy
0 1 1 2 3
      */
            int n=fr.i();
            int m=fr.i();
            Candidate [] candidates=new Candidate[n];
            for(int ni=0;ni<n;++ni)
            {
                candidates[ni]=new Candidate(fr.i(),ni);
            }
            PriorityQueue<Candidate> pq=new PriorityQueue<>();
            int curTime=0;
            int ans=0;
            for(int i=0;i<candidates.length;++i)
            {
                if(curTime+candidates[i].t<=m)
                {
                    candidates[i].ans=ans;
                    curTime+=candidates[i].t;
                    pq.add(candidates[i]);
                }
                else
                {
                    while(pq.size()>=0)
                    {
                        curTime-=pq.remove().t;
                        ++ans;
                        if(curTime+candidates[i].t<=m)
                            break;
                    }
                    pq.add(candidates[i]);
                    curTime+=candidates[i].t;
                    //System.err.println("ans="+ans+"i="+i+" curTime="+curTime);
                    candidates[i].ans=ans;
                }
            }
            for(Candidate c:candidates)
                pw.print(c.ans+" ");
            pw.flush();
            pw.close();
    }
    public static class Candidate implements Comparable<Candidate>
    {
        int t;
        int id;
        int ans;
        public Candidate(int t, int id) {
            this.t = t;
            this.id = id;
        }

        @Override
        public int compareTo(@NotNull Main.Candidate candidate) {
            return Integer.compare(this.t,candidate.t)*-1;
        }
    }
}


import java.util.Scanner;

public class DigitalCounter {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		char[] num = in.next().toCharArray();
		in.close();

		int[] children = { 2, 12, 2, 3, 2, 6, 3, 1, 2 };
		int res = children[num[0]-'0'] * children[num[1]-'0'];
	}

}


import java.util.Scanner;
public class div569 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int res = canculate(n);

        System.out.println(res);
    }
    public static int canculate(int n){
         int res = (n-2)*4+4;
        if (n==2) {
            return 5;
        }
        return res + canculate(n-1);

    }
}


import java.util.Scanner;

public class BinaryProtocol {
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        sc.nextLine();
        String s=sc.nextLine();
        int l=s.length();
        String num="";
        //System.out.println(s);
        int c=0,d=0;
        for(int i=0;i<l;++i){
            char ch=s.charAt(i);
            if(ch=='1'){
                //System.out.println(ch+" "+num);
                if(d>=2){
                    for(int i=1;i<d;++i){
                        num=num+0;
                    }
                }
                d=0;
                c++;
            }
            else if(ch=='0'){
                //System.out.println(ch+" "+s);
                if(c>=1)
                    num=num+c;
                c=0;
                d++;
            }
        }
        if(c!=0)
            num=num+c;
        else if (d>=2){
            for(int i=1;i<=d;++i){
                num=num+0;
            }
        }

        System.out.println(num);
    }
}


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

public final class  Solution1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(),count_0=0,count_1=0;
        String s = in.next();
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<n;i++){
            if(s.charAt(i)=='1'){
                count_1++;
                while(count_0>1){
                    sb.append(0+"");
                    count_0--;
                }
                count_0=0;
            }
            else{
                count_0++;
                if(count_1!=0){
                    sb.append(count_1+"");
                }
                count_1=0;
            }
        }
        if(count_0!=0){
            while(count_0>1){
                sb.append(0+"");
            }
        }
        else{
            sb.append(count_1);
        }
        System.out.println(sb.toString());
    }
}


import java.util.*;
import java.io.*;
public class Main {
    static class Scan {
        private byte[] buf=new byte[1024];
        private int index;
        private InputStream in;
        private int total;
        public Scan()
        {
            in=System.in;
        }
        public int scan()throws IOException
        {
            if(total<0)
            throw new InputMismatchException();
            if(index>=total)
            {
                index=0;
                total=in.read(buf);
                if(total<=0)
                return -1;
            }
            return buf[index++];
        }
        public int scanInt()throws IOException
        {
            int integer=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    integer*=10;
                    integer+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            return neg*integer;
        }
        public double scanDouble()throws IOException
        {
            double doub=0;
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            int neg=1;
            if(n=='-')
            {
                neg=-1;
                n=scan();
            }
            while(!isWhiteSpace(n)&&n!='.')
            {
                if(n>='0'&&n<='9')
                {
                    doub*=10;
                    doub+=n-'0';
                    n=scan();
                }
                else throw new InputMismatchException();
            }
            if(n=='.')
            {
                n=scan();
                double temp=1;
                while(!isWhiteSpace(n))
                {
                    if(n>='0'&&n<='9')
                    {
                        temp/=10;
                        doub+=(n-'0')*temp;
                        n=scan();
                    }
                    else throw new InputMismatchException();
                }
            }
            return doub*neg;
        }
        public String scanString()throws IOException
        {
            StringBuilder sb=new StringBuilder();
            int n=scan();
            while(isWhiteSpace(n))
            n=scan();
            while(!isWhiteSpace(n))
            {
                sb.append((char)n);
                n=scan();
            }
            return sb.toString();
        }
        private boolean isWhiteSpace(int n)
        {
            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
            return true;
            return false;
        }
    }
    static int n,t;
    static double p;
    public static void main(String args[]) throws IOException {
        Scan input=new Scan();
        n=input.scanInt();
        p=input.scanDouble();
        t=input.scanInt();
        double not=1;
        for(int i=0;i<t;i++) {
            not*=(1-p);
        }
        System.out.println(solve(0,0,true));
    }
    public static double solve(int indx,int time,boolean prev) {
//        System.out.println(indx+" "+time+" "+prev);
        if(indx==n || time==t) {
            if(prev) {
                return 1;
            }
            return 0;
        }
        double ways=0;
        if(indx!=n-1 && time!=t-1) {
            ways+=p;
        }
        ways+=p*solve(indx+1,time+1,true);
        ways+=(1-p)*solve(indx,time+1,false);
        return ways;
    }
}


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;

public class A{
	static long mod=1000000007;

    public static void main(String[] args) throws Exception{
    	InputReader in = new InputReader(System.in);
    	PrintWriter pw=new PrintWriter(System.out);

    	//int t=in.readInt();
        //while(t-->0)
        //{

        int n=in.readInt();
        int m=in.readInt();
        int k=in.readInt();
        int a[][]=new int[m][n];
        int l=0,r=0;
        char p='L';
        int c=1;
        for(int i=0,q=0;i<n;i++,q++)
        {
        	for(int j=0;j<m;j++)
        	{
        		a[j][i]=c++;
        		//a[j][i+1]=c++;
        		c++;
        		if(a[j][i]==k)
        		{
        			l=j+1;
        			r=q+1;
        			p='L';
        		}
        		if(a[j][i]==k-1)
        		{
        			l=j+1;
        			r=q+1;
        			p='R';

        		}

        	}
        }
    	//long n=in.readLong();
    	/*int a[]=new int[n];
    	for(int i=0;i<n;i++)
    	{
    		a[i]=in.readInt();
    	}*/
    	//String a=in.readString();

		pw.println(r+" "+l+" "+p);

    	//}

    	pw.close();
    }

public static long gcd(long x,long y)
{
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
}
public static int gcd(int x,int y)
{
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
}
public static int abs(int a,int b)
{
	return (int)Math.abs(a-b);
}
public static long abs(long a,long b)
{
	return (long)Math.abs(a-b);
}
public static int max(int a,int b)
{
	if(a>b)
		return a;
	else
		return b;
}
public static int min(int a,int b)
{
	if(a>b)
		return b;
	else
		return a;
}
public static long max(long a,long b)
{
	if(a>b)
		return a;
	else
		return b;
}
public static long min(long a,long b)
{
	if(a>b)
		return b;
	else
		return a;
}

public static long pow(long n,long p,long m)
{
	 long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    if(result>=m)
	    result%=m;
	    p >>=1;
	    n*=n;
	    if(n>=m)
	    n%=m;
	}
	return result;
}
public static long pow(long n,long p)
{
	long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    p >>=1;
	    n*=n;
	}
	return result;

}
static class Pair implements Comparable<Pair>
{
	int a,b;
	Pair (int a,int b)
	{
		this.a=a;
		this.b=b;
	}

	public int compareTo(Pair o) {
		// TODO Auto-generated method stub
		if(this.a!=o.a)
		return Integer.compare(this.a,o.a);
		else
			return Integer.compare(this.b, o.b);
		//return 0;
	}
	public boolean equals(Object o) {
        if (o instanceof Pair) {
            Pair p = (Pair)o;
            return p.a == a && p.b == b;
        }
        return false;
    }
    public int hashCode() {
        return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
    }

}

static long sort(int a[])
{  int n=a.length;
	int b[]=new int[n];
	return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
 {   long mid=left+(right-left)/2;
	 c= mergeSort(a,b,left,mid);
	 c+=mergeSort(a,b,mid+1,right);
	 c+=merge(a,b,left,mid+1,right); }
	return c;	 }
static long merge(int a[],int  b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]<=a[j]) {b[k++]=a[i++]; }
else	{ b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1)   b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
	a[i] = b[i];  return c;  }

public static int[] radixSort(int[] f)
{
	int[] to = new int[f.length];
	{
		int[] b = new int[65537];
		for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
		for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
		for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
		int[] d = f; f = to;to = d;
	}
	{
		int[] b = new int[65537];
		for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
		for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
		for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
		int[] d = f; f = to;to = d;
	}
	return f;
}
static  class InputReader
{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

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

    public int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars)
        {
            curChar = 0;
            try
            {
                numChars = stream.read(buf);
            } catch (IOException e)
            {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-')
        {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do
        {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }
    public String readLine() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isEndOfLine(c));
        return res.toString();
    }

    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }
    public boolean isSpaceChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next()
    {
        return readString();
    }

    public interface SpaceCharFilter
    {
        public boolean isSpaceChar(int ch);
    }
    public boolean isEndOfLine(int c) {
        return c == '\n' || c == '\r' || c == -1;
    }
}

//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	//StringBuilder sb=new StringBuilder("");
	 //InputReader in = new InputReader(System.in);
	//PrintWriter pw=new PrintWriter(System.out);
	//String line=br.readLine().trim();

	//int t=Integer.parseInt(br.readLine());
  //	while(t-->0)
  	//{
  	//int n=Integer.parseInt(br.readLine());
	//long n=Long.parseLong(br.readLine());
	//String l[]=br.readLine().split(" ");
  //int m=Integer.parseInt(l[0]);
	//int k=Integer.parseInt(l[1]);
	//String l[]=br.readLine().split(" ");
	//l=br.readLine().split(" ");
	/*int a[]=new int[n];
	for(int i=0;i<n;i++)
	{
		a[i]=Integer.parseInt(l[i]);
	}*/
	   //System.out.println(" ");

	//}
}


package elections;

import java.util.Scanner;

public class Elections {
public static void main(String[] args) {
     Scanner input =new Scanner(System.in);
      int n=input.nextInt();
      int numvote=0;
      int a[]=new int[n];
      for(int i=0;i<a.length;i++)
        a[i]=input.nextInt();

      while(true){
           int max=a[0],x=0;
        for(int i=1;i<a.length;i++)
           if(max<=a[i]){
             max=a[i];
             x=i;}
           if(x==0){
             System.out.println(numvote);
             break;}
           else {
              a[0]++;
              a[x]--;
              numvote++;
              }
         }

    }

}


import java.util.*;
public class ph{
	//hi
	static long sum(long a){
		long s=0;
		while(a>0){
			long b=a%10;
			 s=s+b;
			a=a/10;
		}
		return s;
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		long n=sc.nextLong();
		long i,j;
		long g[]=new long[(int)n];
		long a=n%10;
		long b=n-a;
		j=2;
		g[0]=sum(b)+sum(n-b);
		g[1]=sum(n);
		for(i=b-1;i>=0;i=i-10){
			g[(int)j]=sum(i)+sum(n-i);
			j++;
		}
		Arrays.sort(g);
		System.out.println(g[(int)n-1]);
	}
}


import java.util.*;

public class maxsum{
    public int sumofdig(long find){
        int sum = 0;
        while(find > 0){
            sum += find%10;
            find = find/10;
        }
        return sum;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long closehalf = n/2;
        long val1 = 0;
        for(int x = 0; x < 10; x++){
            if((closehalf+x)%10 == 9){
                val1 = closehalf+x;
            }
        }
        long val2 = val1-10;
        System.out.println(Math.max(sumofdig(val1)+sumofdig(n-val1),sumofdig(val2)+sumofdig(n-val2)));
    }
}


import java.io.*;
import java.util.*;
public class java{
   public static void main(String[] args)throws IOException{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String[] s=br.readLine().split(" ");
    int n=Integer.parseInt(s[0]);
    int k=Integer.parseInt(s[1]);
    int[] arr= new int[n];
    s=br.readLine().split(" ");
    for(int i=0;i<n;i++){
     arr[i]= Integer.parseInt(s[i]);
    }
    s=br.readLine().split(" ");
    HashSet<Integer> hs=new HashSet<>();
    for(int i=0;i<k;i++)
      hs.add(Integer.parseInt(s[i]);
    for(int i=0;i<n;i++)
      if(hs.contains(arr[i]))
     System.out.print(arr[i]+" ");
    System.out.println();
   }
}


mport java.util.*;
public class codeforce {
   public static void main(String ae[])
   {
       Scanner sec=new Scanner(System.in);
       int n,m;
       n=sec.nextInt();
       m=sec.nextInt();
       int a[]=new int[n];int b[]=new int[m];
       for(int i=0;i<n;i++)
       {
           a[i]=sec.nextInt();
       }
       for(int i=0;i<m;i++)
       {
           b[i]=sec.nextInt();
       }
       for(int i=0;i<n;i++)
       {
           for(int j=0;j<m;j++)
           {
            if(a[i]==b[j])
            System.out.print(a[i]+" ");
           }
       }
   }
}


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class D {
    private static class BufferedScanner {
        BufferedReader mReader;
        StringTokenizer mTokenizer;

        BufferedScanner(InputStream inputStream) {
            mReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        String next() {
            while (mTokenizer == null || !mTokenizer.hasMoreElements()) {
                String line = readLine();
                if (line != null) {
                    mTokenizer = new StringTokenizer(line);
                } else {
                    break;
                }
            }
            return mTokenizer != null ? mTokenizer.nextToken() : null;
        }

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

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

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

        String nextLine() {
            return readLine();
        }

        private String readLine() {
            try {
                return mReader.readLine();
            } catch (IOException ignore) {
                return null;
            }
        }
    }

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

    private BufferedScanner mReader;
    private PrintStream mWriter;

    private D() throws IOException {
        InputStream actualInputStream;
        if (System.getProperty("ONLINE_JUDGE") != null) {
            actualInputStream = System.in;
        } else {
            File inputFile = new File("in.txt");
            if (!inputFile.exists()) {
                //noinspection ResultOfMethodCallIgnored
                inputFile.createNewFile();
                throw new FileNotFoundException("File wasn't found, but now is created");
            }
            actualInputStream = new FileInputStream(inputFile);
        }
        mReader = new BufferedScanner(new BufferedInputStream(actualInputStream));
        mWriter = System.out;
    }

    private void solve() throws IOException {
        long p = mReader.nextInt();
        long k = mReader.nextInt();
//
        List<Long> coefs = new ArrayList<>();

        long f = p % k;
        long q = p / (-k);

        coefs.add(f);

        while (q != 0) {
            f = (q % k + k) % k;
            q -= (q % k + k) % k;
            q /= -k;

            coefs.add(f);
        }

        System.out.println(coefs.size());
        for (Long coef : coefs) {
            System.out.println(coef);
        }
    }
}


import java.util.*;

public class Sample {
	public static void main(String[] args){

	  Scanner kbd = new Scanner(System.in);
	  int a = kbd.nextInt();
	  int b = kbd.nextInt();
	  int c

	  if(a>b){
	      c = a-b;
	  }else{
	      c = b-a;
	  }

      System.out.print(c);

	 }

}


 import java.util.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.Math;

public class Main{
   public static void main(String args[]) throws Exception
   {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String str = br.readLine();
      int q = 0;
      int a =0;
      int temp_a = 0;
      int temp_q =0;
      int count=0;
      for(int i=0;i<str.length();i++)
      {
         if(str.charAt(i) == 'Q')
         {
            // if(q>0 && a>0)
            // {
            //    count+= Math.max(q,a);
            // }
            if(temp_q!=0 && temp_a!=0)
            {
               q=temp_q;
               a=temp_a;
               temp_q=1;
            }
            else
            {
               temp_q++;
            }
         }
         else if(str.charAt(i) == 'A')
         {
            if(q!=0)
            {
               temp_a++;
            }
         }
      }
      System.out.println(q*a);
   }
}