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 B implements Runnable{

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

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

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

    static class Player implements Comparable<Player> {

    	long need;
    	int first, second;
		public Player(int need, int first, int second) {
			super();
			this.need = need;
			this.first = first;
			this.second = second;
		}

		int delta() {
			return max(first, second) - min(first, second);
		}

		@Override
		public int compareTo(Player other) {
			return -(this.delta() - other.delta());
		}

    }

    private void solve() {
    	int n = readInt();
    	int s = readInt();

    	Player[] players = new Player[n];
    	for (int i = 0; i < n; ++i) {
    		players[i] = new Player(readInt(), readInt(), readInt());
    	}

    	List<Player> first = new ArrayList<Player>();
    	List<Player> second = new ArrayList<Player>();

    	for (Player player : players) {
    		if (player.first > player.second) first.add(player);
    		else second.add(player);
    	}

    	Collections.sort(first);
    	Collections.sort(second);

    	int firstSize = first.size(), secondSize = second.size();
    	long[] prefFirst = new long[firstSize + 1], prefSecond = new long[secondSize + 1];

    	for (int i = 0; i < firstSize; ++i) {
    		Player player = first.get(i);
    		prefFirst[i + 1] = prefFirst[i] + player.delta() * player.need;
    	}

    	for (int i = 0; i < secondSize; ++i) {
    		Player player = second.get(i);
    		prefSecond[i + 1] = prefSecond[i] + player.delta() * player.need;
    	}

    	long answer = 0;
    	for (Player player : players) {
    		answer += min(player.first, player.second) * player.need;
    	}

    	long totalSum = 0;
    	for (Player player : players) {
    		totalSum += player.need;
    	}

    	long totalNeed = (totalSum - 1) / s + 1;

    	long left = 0, right = totalNeed;
    	while (right - left >= 50) {
    		long mid1 = left + (right - left) / 3;
    		long mid2 = right - (right - left) / 3;

    		long firstAnswer = f(mid1, totalNeed - mid1, s, first, second);
    		long secondAnswer = f(mid2, totalNeed - mid2, s, first, second);

    		if (firstAnswer >= secondAnswer) {
    			right = mid2;
    		} else {
    			left = mid1;
    		}
    	}

    	long best = left;
    	long bestResult = f(left, totalNeed - left, s, first, second);
    	for (long mid = left; mid <= right; ++mid) {
    		long result = f(mid, totalNeed - mid, s, first, second);
    		if (result > bestResult) {
    			bestResult = result;
    			best = mid;
    		}
    	}

    	answer += bestResult;
    	out.println(answer);
    }

    long f(long firstPizza, long secondPizza, long pieces, List<Player> first, List<Player> second) {
    	long answer = 0;

    	firstPizza *= pieces;
    	secondPizza *= pieces;

    	for (Player player : first) {
    		long can = min(player.need, firstPizza);
    		firstPizza -= can;
    		answer += can * player.delta();
    	}

    	for (Player player : second) {
    		long can = min(player.need, secondPizza);
    		secondPizza -= can;
    		answer += can * player.delta();
    	}

    	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 B(), "", 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<IntIndexPair>() {

            @Override
            public int compare(IntIndexPair indexPair1, 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<IntIndexPair>() {

            @Override
            public int compare(IntIndexPair indexPair1, 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 final 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>();

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

            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 = 20;

        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;
        }
    }

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


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

public class B2 {
    FastScanner in;
    PrintWriter out;

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

    class Person {
        long s, a, b;

        public Person(int s, int a, int b) {
            this.s = s;
            this.a = a;
            this.b = b;
        }
    }

    void solve() throws IOException {
        int n = in.nextInt();
        long s = in.nextInt();
        Person[] people = new Person[n];
        Arrays.setAll(people, i -> new Person(in.nextInt(), in.nextInt(), in.nextInt()));
        long s1 = Arrays.stream(people).filter(p -> p.a < p.b).mapToLong(p -> p.s).sum();
        long s2 = Arrays.stream(people).filter(p -> p.a == p.b).mapToLong(p -> p.s).sum();
        long s3 = Arrays.stream(people).filter(p -> p.a > p.b).mapToLong(p -> p.s).sum();
        long dif = 0;
        if (s1 % s + s2 + s3 % s <= s) {
            long dif1 = 0, dif2 = 0;
            {
                Arrays.sort(people, Comparator.comparingLong(p -> p.a - p.b));
                long s0 = 0;
                long ns = s1 / s * s;
                for (int i = 0; i < n; i++) {
                    if (people[i].a >= people[i].b) break;
                    s0 += people[i].s;
                    if (s0 > ns) {
                        dif1 += (people[i].s - Math.max(0, ns - (s0 - people[i].s))) * Math.abs(people[i].a - people[i].b);
                    }
                }
            }

            {
                Arrays.sort(people, Comparator.comparingLong(p -> p.b - p.a));
                long s0 = 0;
                long ns = s3 / s * s;
                for (int i = 0; i < n; i++) {
                    if (people[i].a <= people[i].b) break;
                    s0 += people[i].s;
                    if (s0 > ns) {
                        dif2 += (people[i].s - Math.max(0, ns - (s0 - people[i].s))) * Math.abs(people[i].a - people[i].b);
                    }
                }
            }
            dif = Math.min(dif1, dif2);
        } else {
            dif = 0;
        }
        out.println(Arrays.stream(people).filter(p -> p.a <= p.b).mapToLong(p -> p.s * p.b).sum()
                + Arrays.stream(people).filter(p -> p.a > p.b).mapToLong(p -> p.s * p.a).sum()
                - dif);
    }

    void run() {
        try {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
            solve();

            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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


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

public class B {
	FastScanner in;
	PrintWriter out;
	boolean systemIO = true;

	public void quickSort(int[] a, int from, int to) {
		if (to - from <= 1) {
			return;
		}
		int i = from;
		int j = to - 1;
		int x = a[from + (new Random()).nextInt(to - from)];
		while (i <= j) {
			while (a[i] < x) {
				i++;
			}
			while (a[j] > x) {
				j--;
			}
			if (i <= j) {
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
				i++;
				j--;
			}
		}
		quickSort(a, from, j + 1);
		quickSort(a, j + 1, to);
	}

	public void quickSort(P[] a, int from, int to) {
		if (to - from <= 1) {
			return;
		}
		int i = from;
		int j = to - 1;
		P x = a[from + (new Random()).nextInt(to - from)];
		while (i <= j) {
			while (a[i].compareTo(x) < 0) {
				i++;
			}
			while (a[j].compareTo(x) > 0) {
				j--;
			}
			if (i <= j) {
				P t = a[i];
				a[i] = a[j];
				a[j] = t;
				i++;
				j--;
			}
		}
		quickSort(a, from, j + 1);
		quickSort(a, j + 1, to);
	}

	public class P implements Comparable<P> {
		long s;
		long a;
		long b;
		long base;
		long delta;

		public P(long s, long a, long b) {
			this.a = a;
			this.b = b;
			this.s = s;
		}

		@Override
		public int compareTo(P o) {
			if((a - b) - (o.a - o.b) > 0) {
				return 1;
			}
			if ((a - b) - (o.a - o.b) < 0) {
				return -1;
			}
			return 0;
		}

	}

	public long get(long b) {
		if (b < 0 || b > number) {
			return -1;
		}
		long h = 0;
		long s1 = b * s;
		long s2 = (number - b) * s;
		int last = -1;
		P free = new P(0, 0, 0);
		for (int i = 0; i < p.length; i++) {
			if (p[i].b > p[i].a) {
				if (p[i].s <= s1) {
					s1 -= p[i].s;
					h += p[i].s * p[i].b;
					last = i;
				} else {
					last = i;
					free = new P(p[i].s - s1, p[i].a, p[i].b);
					h += s1 * p[i].b;
					s1 = 0;
					break;
				}
			} else {
				break;
			}
		}
		int first = p.length;
		s2 -= free.s;
		h += free.s * free.a;
		free = new P(0, 0, 0);
		for (int i = p.length - 1; i > last; i--) {
			if (p[i].s <= s2) {
				s2 -= p[i].s;
				h += p[i].s * p[i].a;
				first = i;
			} else {
				first = i;
				free = new P(p[i].s - s2, p[i].a, p[i].b);
				h += s2 * p[i].a;
				s2 = 0;
				break;
			}
		}
		h += free.s * free.b;
		for (int i = last + 1; i < first; i++) {
			h += p[i].s * p[i].b;
		}
		return h;
	}

	P[] p;
	long number;
	long s;

	public void solve() {
		int n = in.nextInt();
		s = in.nextLong();
		p = new P[n];
		long sum = 0L;
		for (int i = 0; i < p.length; i++) {
			p[i] = new P(in.nextLong(), in.nextLong(), in.nextLong());
			sum += p[i].s;
		}
		number = 0;
		if (sum % s == 0) {
			number = sum / s;
		} else {
			number = sum / s + 1;
		}
		quickSort(p, 0, n);
		long l = -1;
		long r = number + 1;
		while (l + 2 < r) {
			long left = l + (r - l) / 3;
			long right = l + 2 * (r - l) / 3;
			if (get(left) < get(right)) {
				l = left;
			} else {
				r = right;
			}
		}
		System.out.println(Math.max(Math.max(get(l), get(l + 1)), get(l + 2)));
	}

	public void run() {
		try {
			if (systemIO) {
				in = new FastScanner(System.in);
				out = new PrintWriter(System.out);
			} else {
				in = new FastScanner(new File("input.txt"));
				out = new PrintWriter(new File("output.txt"));
			}
			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

		String nextLine() {
			try {
				return br.readLine();
			} catch (IOException e) {
				return null;
			}
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

	}

	// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
	public static void main(String[] args) {
		new B().run();
	}
}


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

public class B {
	FastScanner in;
	PrintWriter out;
	boolean systemIO = true;

	public void quickSort(int[] a, int from, int to) {
		if (to - from <= 1) {
			return;
		}
		int i = from;
		int j = to - 1;
		int x = a[from + (new Random()).nextInt(to - from)];
		while (i <= j) {
			while (a[i] < x) {
				i++;
			}
			while (a[j] > x) {
				j--;
			}
			if (i <= j) {
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
				i++;
				j--;
			}
		}
		quickSort(a, from, j + 1);
		quickSort(a, j + 1, to);
	}

	public void quickSort(P[] a, int from, int to) {
		if (to - from <= 1) {
			return;
		}
		int i = from;
		int j = to - 1;
		P x = a[from + (new Random()).nextInt(to - from)];
		while (i <= j) {
			while (a[i].compareTo(x) < 0) {
				i++;
			}
			while (a[j].compareTo(x) > 0) {
				j--;
			}
			if (i <= j) {
				P t = a[i];
				a[i] = a[j];
				a[j] = t;
				i++;
				j--;
			}
		}
		quickSort(a, from, j + 1);
		quickSort(a, j + 1, to);
	}

	public class P implements Comparable<P> {
		long s;
		long a;
		long b;
		long base;
		long delta;

		public P(long s, long a, long b) {
			this.a = a;
			this.b = b;
			this.s = s;
		}

		@Override
		public int compareTo(P o) {
			if((a - b) - (o.a - o.b) > 0) {
				return 1;
			}
			if ((a - b) - (o.a - o.b) < 0) {
				return -1;
			}
			return 0;
		}

	}

	public long get(long b) {
		if (b < 0 || b > number) {
			return -1;
		}
		long h = 0;
		long s1 = b * s;
		long s2 = (number - b) * s;
		int last = 0;
		P free = new P(0, 0, 0);
		for (int i = 0; i < p.length; i++) {
			if (p[i].b > p[i].a) {
				if (p[i].s <= s1) {
					s1 -= p[i].s;
					h += p[i].s * p[i].b;
					last = i;
				} else {
					last = i;
					free = new P(p[i].s - s1, p[i].a, p[i].b);
					h += s1 * p[i].b;
					s1 = 0;
					break;
				}
			} else {
				break;
			}
		}
		int first = p.length;
		s2 -= free.s;
		h += free.s * free.a;
		free = new P(0, 0, 0);
		for (int i = p.length - 1; i > last; i--) {
			if (p[i].s <= s2) {
				s2 -= p[i].s;
				h += p[i].s * p[i].a;
				first = i;
			} else {
				first = i;
				free = new P(p[i].s - s2, p[i].a, p[i].b);
				h += s2 * p[i].a;
				s2 = 0;
				break;
			}
		}
		h += free.s * free.b;
		for (int i = last + 1; i < first; i++) {
			h += p[i].s * p[i].b;
		}
		return h;
	}

	P[] p;
	long number;
	long s;

	public void solve() {
		int n = in.nextInt();
		s = in.nextLong();
		p = new P[n];
		long sum = 0L;
		for (int i = 0; i < p.length; i++) {
			p[i] = new P(in.nextLong(), in.nextLong(), in.nextLong());
			sum += p[i].s;
		}
		number = 0;
		if (sum % s == 0) {
			number = sum / s;
		} else {
			number = sum / s + 1;
		}
		quickSort(p, 0, n);
		long l = -1;
		long r = number + 1;
		while (l + 2 < r) {
			long left = l + (r - l) / 3;
			long right = l + 2 * (r - l) / 3;
			if (get(left) < get(right)) {
				l = left;
			} else {
				r = right;
			}
		}
		System.out.println(Math.max(Math.max(get(l), get(l + 1)), get(l + 2)));
	}

	public void run() {
		try {
			if (systemIO) {
				in = new FastScanner(System.in);
				out = new PrintWriter(System.out);
			} else {
				in = new FastScanner(new File("input.txt"));
				out = new PrintWriter(new File("output.txt"));
			}
			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

		String nextLine() {
			try {
				return br.readLine();
			} catch (IOException e) {
				return null;
			}
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

	}

	// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
	public static void main(String[] args) {
		new B().run();
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            long S = in.nextLong();
            TaskB.Person[] p = new TaskB.Person[n];
            for (int i = 0; i < n; ++i) p[i] = new TaskB.Person();
            long need = 0;
            for (int i = 0; i < n; ++i) {
                p[i].s = in.nextInt();
                p[i].a = in.nextInt();
                p[i].b = in.nextInt();
                need += p[i].s;
            }
            long am = (need + S - 1) / S;
            long extra = am * S - need;
            p = Arrays.copyOf(p, n + 1);
            p[n] = new TaskB.Person();
            p[n].s = extra;
            ++n;
            Arrays.sort(p, new Comparator<TaskB.Person>() {

                public int compare(TaskB.Person o1, TaskB.Person o2) {
                    return (o1.a - o1.b) - (o2.a - o2.b);
                }
            });
            long res = 0;
            for (TaskB.Person pp : p) res += pp.s * pp.a;
            long cur = res;
            long tail = 0;
            for (TaskB.Person pp : p) {
                if (tail + pp.s < S) {
                    tail += pp.s;
                    cur += pp.s * (pp.b - pp.a);
                    continue;
                }
                long by = S - tail;
                tail += by;
                pp.s -= by;
                cur += (pp.b - pp.a) * by;
                res = Math.max(res, cur);
                long whole = pp.s / S;
                cur += (pp.b - pp.a) * S * whole;
                pp.s -= S * whole;
                res = Math.max(res, cur);
                tail = pp.s;
                cur += tail * (pp.b - pp.a);
            }
            if (tail != 0) throw new RuntimeException();
            out.println(res);
        }

        static class Person {
            long s;
            int a;
            int b;

        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

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

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

    }
}


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int MAXN = 100010;
int _w;

int n, m, s[MAXN], a[MAXN], b[MAXN];
vector<pii> atob, btoa;

int main() {
	_w = scanf( "%d%d", &n, &m );
	ll cnt = 0, cnta = 0, cntb = 0, ans = 0;
	for( int i = 0; i < n; ++i ) {
		_w = scanf( "%d%d%d", s+i, a+i, b+i );
		cnt += s[i];
		if( a[i] > b[i] ) {
			cnta += s[i];
			ans += (ll)s[i] * a[i];
			atob.push_back( pii(a[i]-b[i], s[i]) );
		} else {
			cntb += s[i];
			ans += (ll)s[i] * b[i];
			btoa.push_back( pii(b[i]-a[i], s[i]) );
		}
	}
	sort(atob.begin(), atob.end());
	sort(btoa.begin(), btoa.end());
	ll buy = (cnt / m) + bool(cnt % m);
	ll buya = (cnta / m) + bool(cnta % m);
	ll buyb = (cntb / m) + bool(cntb % m);
	if( buya + buyb > buy ) {
		ll changea = cnta % m, ansa = ans;
		ll changeb = cntb % m, ansb = ans;
		for( int i = 0; i < (int)atob.size() && changea; ++i ) {
			ll change = min(changea, (ll)atob[i].second);
			ansa -= (ll)atob[i].first * change;
			changea -= change;
		}
		for( int i = 0; i < (int)btoa.size() && changeb; ++i ) {
			ll change = min(changeb, (ll)btoa[i].second);
			ansb -= (ll)btoa[i].first * change;
			changeb -= change;
		}
		ans = max(ansa, ansb);
	}
	printf( "%lld\n", ans );
	return 0;
}


#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<utility>
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 233;
ll ans = 0;
int a[maxn],b[maxn],s[maxn],ord[maxn];
bool cmp(int A,int B)
{
	return (b[A]-a[A])>(b[B]-a[B]);
}
int main()
{
	int n,S;cin>>n>>S;
	ll tot = 0;
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d%d",&s[i],&a[i],&b[i]);
		ans += 1LL*s[i]*a[i];
		ord[i]=i;
		tot += s[i];
	}
//	cout<<"!"<<tot<<" "<<ans<<endl;
	if(tot%S!=0)
	{
		int nt = 1LL*(tot/S+1)*S;
		n++;
		a[n]=b[n]=0;
		s[n] = nt-tot;
		ord[n] = n;
	}
	sort(ord+1,ord+1+n,cmp);
	int cur = 0;
	ll buf = 0,sum = 0;
	for(int i=1;i<=n;i++)
	{
		int x = ord[i];
//		cout <<"!"<<x<<endl;
		if(s[x]+cur>=S)
		{
			ll tmp = S-cur;
			buf += tmp*(b[x]-a[x]);
			s[x] -= tmp;
			if(buf<=0)break;
			sum += buf;
			cur = buf = 0;

			ll cnt = s[x]/S;
//			cout<<"!"<<cnt<<endl;
			if(b[x]-a[x]<=0)break;
			sum += cnt*(b[x]-a[x])*S;
			s[x] %= S;
		}
		cur += s[x];
		buf += s[x]*(b[x]-a[x]);
	}
	cout << ans + sum << endl;
	return 0;
}


#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<utility>
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 233;
ll ans = 0;
int a[maxn],b[maxn],s[maxn],ord[maxn];
bool cmp(int A,int B)
{
	return (b[A]-a[A])>(b[B]-a[B]);
}
int main()
{
	int n,S;cin>>n>>S;
	ll tot = 0;
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d%d",&s[i],&a[i],&b[i]);
		ans += 1LL*s[i]*a[i];
		ord[i]=i;
		tot += s[i];
	}
//	cout<<"!"<<tot<<" "<<ans<<endl;
	if(tot%S!=0)
	{
		int nt = 1LL*(tot/S+1)*S;
		n++;
		a[n]=b[n]=0;
		s[n] = nt-tot;
		ord[n] = n;
	}
	sort(ord+1,ord+1+n,cmp);
	int cur = 0;
	ll buf = 0,sum = 0;
	for(int i=1;i<=n;i++)
	{
		int x = ord[i];
//		cout <<"!"<<x<<endl;
		if(s[x]+cur>=S)
		{
			ll tmp = S-cur;
			buf += tmp*(b[x]-a[x]);
			s[x] -= tmp;
			if(buf<=0)break;
			sum += buf;
			cur = buf = 0;

			ll cnt = s[x]/S;
//			cout<<"!"<<cnt<<endl;
			if(b[x]-a[x]<=0)break;
			sum += cnt*(b[x]-a[x])*S;
			s[x] %= S;
		}
		cur += s[x];
		buf += 1LL*s[x]*(b[x]-a[x]);
	}
	cout << ans + sum << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 5e5 + 5;
VI num;
int n;

void add(int index, int sum, bool &judge) {
	if (sum == n) {
		judge = true;
		return;
	};
	if (index == num.size() || sum > n) return;
	add(index + 1, sum, judge);
	add(index + 1, sum + num[index], judge);
}

int main() {
	int t, tmp, pre, pos;
	cin >> t;
	while (t--) {
		num.clear();
		cin >> n;
		pre = -1; pos = 0;
		for (int i = 0; i < 2 * n; i++) {
			cin >> tmp;
			if (tmp > pre) {
				pre = tmp;
				if (pos) num.pb(i - pos);
				pos = i;
			}
		}
		if (pos < 2 * n) num.pb(2 * n - pos);
		bool judge = false;
		add(0, 0, judge);
		if (judge) cout << "YES" << endl;
		else cout << "NO" << endl;

	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 4e3 + 7;
VI num;
int dp[maxn];
int n;
/*
void add(int index, int sum, bool &judge) {
	if (sum == n) {
		judge = true;
		return;
	};
	if (index == num.size() || sum > n) return;
	add(index + 1, sum, judge);
	add(index + 1, sum + num[index], judge);
}*/

int main() {
	int t, tmp, pre, pos;
	cin >> t;
	while (t--) {
		cin >> n;
		memset(dp, 0, sizeof(dp));
		num.clear();
		pre = -1; pos = 0;
		for (int i = 0; i < 2 * n; i++) {
			cin >> tmp;
			if (tmp > pre) {
				pre = tmp;
				if (pos) num.pb(i - pos);
				pos = i;
			}
		}
		if (pos < 2 * n) num.pb(2 * n - pos);
		/*bool judge = false;
		add(0, 0, judge);
*/
		for (int i = 0; i < num.size(); ++i) {
			for (int j = n; j >= num[i]; --j) {
				dp[j] = max(dp[j], dp[j - num[i]] + num[i]);
			}
		}
		if (dp[n] == n) cout << "YES" << endl;
		else cout << "NO" << endl;

	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define mod 1000000007
#define mod2 998244353
#define pi pair<ll,ll>
#define pii pair<ll,pair<ll,ll>>
#define vi vector<ll>
#define pb push_back
#define ld long double
#define vpi vector<pair<ll,ll>>
#define vvi vector<vector<ll>>

#define debug(a) { cout << #a << " = " << a << endl;}

void sep() {
    cout << "-------------BLOCK-----------------\n";
}

template<typename T>
void debugv(vector<T> arr) {
    for (auto t: arr)
        cout << t << " ";
    cout << "\n";
}

template<typename T>
void debugarr(T arr, int n) {
    for (int i=0;i<n;i++) cout << arr[i] << " ";
    cout << "\n";
}

ll __min(ll a, ll b) {
    return a < b ? a : b;
}

ll __max(ll a, ll b) {
    return a > b ? a : b;
}

const int maxn = 1e6+100;
ll arr[maxn], n, m, t, k, q;
unordered_map<ll,ll> u;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin>>t;
    while (t--) {
        cin>>n;
        for (int i=1;i<=2*n;i++) cin>>arr[i];
        ll now = 2*n+1;
        vi grps;
        while (now > 1) {
            int idx=max_element(arr+1,arr+now)-arr;
            grps.pb(now-idx);
            now=idx;
        }
        bitset<maxn> f(1);
        for (int i=0;i<grps.size();i++)
            f = f | (f<<grps[i]);
        if (f[n]) cout << "YES";
        else cout << "NO";
        cout << endl;
    }
}


#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define mod 1000000007
#define mod2 998244353
#define pi pair<ll,ll>
#define pii pair<ll,pair<ll,ll>>
#define vi vector<ll>
#define pb push_back
#define ld long double
#define vpi vector<pair<ll,ll>>
#define vvi vector<vector<ll>>

#define debug(a) { cout << #a << " = " << a << endl;}

void sep() {
    cout << "-------------BLOCK-----------------\n";
}

template<typename T>
void debugv(vector<T> arr) {
    for (auto t: arr)
        cout << t << " ";
    cout << "\n";
}

template<typename T>
void debugarr(T arr, int n) {
    for (int i=0;i<n;i++) cout << arr[i] << " ";
    cout << "\n";
}

ll __min(ll a, ll b) {
    return a < b ? a : b;
}

ll __max(ll a, ll b) {
    return a > b ? a : b;
}

const int maxn = 4e6+100;
ll arr[maxn], n, m, t, k, q;
unordered_map<ll,ll> u;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin>>t;
    while (t--) {
        cin>>n;
        set<ll> s;
        for (int i=0;i<2*n;i++) {cin>>arr[i];s.insert(i+1);}
        vi grps;
        ll looking=2*n;
        ll cnt=0;
        for (int i=2*n-1;i>=0;i--) {
            if (arr[i]==looking) {
                grps.pb(cnt+1);
                cnt=0;
                s.erase(looking);
                if (s.empty()) {
                    if (i != 0) {grps.pb(i);}
                    break;
                }
                looking = *s.rbegin();
            } else {
                cnt++;
            }
        }
        reverse(grps.begin(),grps.end());
        ll si = grps.size();
        vvi dp(si+1, vi(n+1, 0));
        for (int i=0;i<=n;i++) dp[0][i]=0;
        for (int i=0;i<=si;i++) dp[i][0]=1;
        for (int i=1;i<=si;i++) {
            for (int j=1;j<=n;j++) {
                int a = (j - grps[i-1]) >= 0 ? dp[i-1][j-grps[i-1]] : 0;
                int b = dp[i-1][j];
                dp[i][j] = (a || b) ? 1 : 0;
            }
        }
        bool pos=false;
        for (int i=0;i<=si;i++)
            if (dp[i][n]) {
                pos=true;
                break;
            }
        if (pos) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}


#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define mod 1000000007
#define mod2 998244353
#define pi pair<ll,ll>
#define pii pair<ll,pair<ll,ll>>
#define vi vector<ll>
#define pb push_back
#define ld long double
#define vpi vector<pair<ll,ll>>
#define vvi vector<vector<ll>>

#define debug(a) { cout << #a << " = " << a << endl;}

void sep() {
    cout << "-------------BLOCK-----------------\n";
}

template<typename T>
void debugv(vector<T> arr) {
    for (auto t: arr)
        cout << t << " ";
    cout << "\n";
}

template<typename T>
void debugarr(T arr, int n) {
    for (int i=0;i<n;i++) cout << arr[i] << " ";
    cout << "\n";
}

ll __min(ll a, ll b) {
    return a < b ? a : b;
}

ll __max(ll a, ll b) {
    return a > b ? a : b;
}

const int maxn = 4e6+100;
ll arr[maxn], n, m, t, k, q;
unordered_map<ll,ll> u;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin>>t;
    while (t--) {
        cin>>n;
        set<ll> s;
        for (int i=0;i<2*n;i++) {cin>>arr[i];s.insert(i+1);}
        vi grps;
        ll looking=2*n;
        ll cnt=0;
        for (int i=2*n-1;i>=0;i--) {
            if (arr[i]==looking) {
                grps.pb(cnt+1);
                cnt=0;
                s.erase(looking);
                if (s.empty()) {
                    if (i != 0) {grps.pb(i);}
                    break;
                }
                looking = *s.rbegin();
            } else {
                cnt++;
            }
        }
        reverse(grps.begin(),grps.end());
        ll si = grps.size();
        vvi dp(si+1, vi(n+1, 0));
        for (int i=0;i<=n;i++) dp[0][i]=0;
        for (int i=0;i<=si;i++) dp[i][0]=1;
        for (int i=1;i<=si;i++) {
            for (int j=1;j<=n;j++) {
                int a = (j - grps[i-1]) >= 0 ? dp[i-1][j-grps[i-1]] : 0;
                int b = dp[i-1][j];
                dp[i][j] = (a || b) ? 1 : 0;
            }
        }
        bool pos=false;
        for (int i=1;i<=si;i++)
            if (dp[i][n]) {
                pos=true;
                break;
            }
        if (pos) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

void solve() {
	int n;
	cin >> n;
	vector<int> init;
	int cnt = 1;
	int mx;
	cin >> mx;
	for(int i = 1; i < 2 * n; i++) {
		int cur;
		cin >> cur;
		if(cur < mx) cnt += 1;
		else {
			init.push_back(cnt);
			cnt = 1;
			mx = cur;
		}
	}
	init.push_back(cnt);
	int s = init.size();
	bool dp[s][n + 1];
	for(int i = 0; i < s; i++) {
		for(int j = 1; j <= n; j++) {
			dp[i][j] = false;
		}
	}
	dp[0][init[0]] = true;
	for(int i = 1; i < s; i++) {
		int cur = init[i];
		dp[i][cur] = true;
		for(int j = 1; j <= n; j++) {
			if(cur == j) continue;
			dp[i][j] = dp[i - 1][j];
			if(cur < j) {
				dp[i][j] |= dp[i - 1][j - cur];
			}
		}
	}
	if(dp[s - 1][n] == true) {
		cout << "YES" << endl;
	}else {
		cout << "NO" << endl;
	}
}

int main () {
	int t;
	cin >> t;
	for(int tt = 0; tt < t; tt++) solve();
	return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

void solve() {
	int n;
	cin >> n;
	vector<int> init;
	int cnt = 1;
	int mx;
	cin >> mx;
	for(int i = 1; i < 2 * n; i++) {
		int cur;
		cin >> cur;
		if(cur < mx) cnt += 1;
		else {
			init.push_back(cnt);
			cnt = 1;
			mx = cur;
		}
	}
	init.push_back(cnt);
	int s = init.size();
	bool dp[s][n + 1];
	for(int i = 0; i < s; i++) {
		for(int j = 1; j <= n; j++) {
			dp[i][j] = false;
		}
	}
	if(init[0] <= n) dp[0][init[0]] = true;
	for(int i = 1; i < s; i++) {
		int cur = init[i];
		dp[i][cur] = true;
		for(int j = 1; j <= n; j++) {
			if(cur == j) continue;
			dp[i][j] = dp[i - 1][j];
			if(cur < j) {
				dp[i][j] |= dp[i - 1][j - cur];
			}
		}
	}
	if(dp[s - 1][n] == true) {
		cout << "YES" << endl;
	}else {
		cout << "NO" << endl;
	}
}

int main () {
	int t;
	cin >> t;
	for(int tt = 0; tt < t; tt++) solve();
	return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

void solve() {
	int n;
	cin >> n;
	vector<int> init;
	int cnt = 1;
	int mx;
	cin >> mx;
	for(int i = 1; i < 2 * n; i++) {
		int cur;
		cin >> cur;
		if(cur < mx) cnt += 1;
		else {
			init.push_back(cnt);
			cnt = 1;
			mx = cur;
		}
	}
	init.push_back(cnt);
	int s = init.size();
	bool dp[s][n + 1];
	for(int i = 0; i < s; i++) {
		for(int j = 1; j <= n; j++) {
			dp[i][j] = false;
		}
	}
	if(init[0] <= n) dp[0][init[0]] = true;
	for(int i = 1; i < s; i++) {
		int cur = init[i];
		if(cur <= n) dp[i][cur] = true;
		for(int j = 1; j <= n; j++) {
			if(cur == j) continue;
			dp[i][j] = dp[i - 1][j];
			if(cur < j) {
				dp[i][j] |= dp[i - 1][j - cur];
			}
		}
	}
	if(dp[s - 1][n] == true) {
		cout << "YES" << endl;
	}else {
		cout << "NO" << endl;
	}
}

int main () {
	int t;
	cin >> t;
	for(int tt = 0; tt < t; tt++) solve();
	return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

void solve() {
	int n;
	cin >> n;
	vector<int> init;
	int cnt = 1;
	int mx;
	cin >> mx;
	for(int i = 1; i < 2 * n; i++) {
		int cur;
		cin >> cur;
		if(cur < mx) cnt += 1;
		else {
			init.push_back(cnt);
			cnt = 1;
			mx = cur;
		}
	}
	init.push_back(cnt);
	int s = init.size();
	bool dp[s][n];
	for(int i = 0; i < s; i++) {
		for(int j = 1; j <= n; j++) {
			dp[i][j] = false;
		}
	}
	dp[0][init[0]] = true;
	for(int i = 1; i < s; i++) {
		int cur = init[i];
		dp[i][cur] = true;
		for(int j = 1; j <= n; j++) {
			if(cur == j) continue;
			dp[i][j] = dp[i - 1][j];
			if(cur < j) {
				dp[i][j] |= dp[i - 1][j - cur];
			}
		}
	}
	if(dp[s - 1][n] == true) {
		cout << "YES" << endl;
	}else {
		cout << "NO" << endl;
	}
}

int main () {
	int t;
	cin >> t;
	for(int tt = 0; tt < t; tt++) solve();
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=4e3+5;
int a[N];
bool vis[N];
int main(){
	int t;scanf("%d",&t);
	while(t--){
		int n;scanf("%d",&n);
		for(int i=1;i<=2*n;++i){
			vis[i]=false;
		}
		int siza=0,sizb=0;
		for(int i=1;i<=2*n;++i){
			scanf("%d",&a[i]);
		}
		int cunt;
		for(int i=2*n;i>=1;){
			int maxs=-1;cunt=0;
			for(int j=2*n;j>=1;--j)
				if(vis[j]==false){
					maxs=j;break;
				}
			while(a[i]!=maxs && i>=1){
				cunt++;i--;
				vis[a[i]]=true;
			}
			if(i>=1){
				cunt++;vis[maxs]=true;i--;
			}

//			cout<<"cunt: "<<cunt<<"\n";
			if(siza<=sizb) siza+=cunt;
			else sizb+=cunt;
		}
		if(siza!=sizb) puts("NO");
		else puts("YES");
	}
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=4e3+5;
int a[N];
bool vis[N];
vector<int>ve;
bitset<5000> bi;
int main(){
	int t;scanf("%d",&t);
	while(t--){
		ve.clear();
		bi&=0;
		int n;scanf("%d",&n);
		for(int i=1;i<=2*n;++i){
			vis[i]=false;
		}
		for(int i=1;i<=2*n;++i){
			scanf("%d",&a[i]);
		}
		int cunt;
		for(int i=2*n;i>=1;){
			int maxs=0;cunt=0;
			for(int j=2*n;j>=1;--j)
				if(vis[j]==false){
					maxs=j;break;
				}
			while(a[i]!=maxs && i>=1){
				vis[a[i]]=true;
				cunt++;i--;
			}
			if(i>=1){
				cunt++;vis[maxs]=true;i--;
			}
//			cout<<cunt<<"\n";
			bi|=(bi<<cunt);
			bi[cunt]=1;
		}
//		cout<<(bi.to_string())<<"\n";
		if(bi[n]) puts("YES");
		else puts("NO");
	}
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=4e3+5;
int a[N];
bool vis[N];
vector<int>ve;
bitset<4000> bi;
int main(){
	int t;scanf("%d",&t);
	while(t--){
		ve.clear();
		bi&=0;
		int n;scanf("%d",&n);
		for(int i=1;i<=2*n;++i){
			vis[i]=false;
		}
		int siza=0,sizb=0;
		for(int i=1;i<=2*n;++i){
			scanf("%d",&a[i]);
		}
		int cunt;
		for(int i=2*n;i>=1;){
			int maxs=-1;cunt=0;
			for(int j=2*n;j>=1;--j)
				if(vis[j]==false){
					maxs=j;break;
				}
			while(a[i]!=maxs && i>=1){
				cunt++;i--;
				vis[a[i]]=true;
			}
			if(i>=1){
				cunt++;vis[maxs]=true;i--;
			}
//			cout<<cunt<<"\n";
			bi|=(bi<<cunt);
			bi[cunt]=1;
		}
//		cout<<(bi.to_string())<<"\n";
		if(bi[n]) puts("YES");
		else puts("NO");
	}
}


#include <bits/stdc++.h>
using namespace std;

int const N = 4e3 + 7;
int ar[N];

bool dp[N];
void solve()
{
	int n;
	cin >> n;

	for (int i = 0; i < 2*n; ++i)
		cin >> ar[i];

	vector<int> blocks;

	int mx = ar[0], ctr = 1;
	for (int i = 1; i <= 2*n; ++i)
	{
		if (mx < ar[i] || i == 2*n)
		{
			if (ctr != 0)
				blocks.push_back(ctr);
			ctr = 1;
			mx = ar[i];
		}
		else
		{
			ctr++;
		}
	}

	memset(dp, false, sizeof(dp));
	dp[0] = true;
	for (int i = 0; i < blocks.size(); ++i)
	{
		for (int j = n; j >= blocks[i]; --j)
		{
			dp[j] = (dp[j] || dp[j-blocks[i]]);
		}
	}

	cout << (dp[n] ? "YES\n" : "NO\n");
}

int main()
{
	int t;
	cin >> t;

	while (t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int const N = 4e3 + 7;
int ar[N];

void solve()
{
	int n;
	cin >> n;

	for (int i = 0; i < 2*n; ++i)
		cin >> ar[i];

	vector<int> blocks;

	int mx = ar[0], ctr = 1;
	for (int i = 1; i <= 2*n; ++i)
	{
		if (mx < ar[i] || i == 2*n)
		{
			if (ctr != 0)
				blocks.push_back(ctr);
			ctr = 1;
			mx = ar[i];
		}
		else
		{
			ctr++;
		}
	}

	vector<pair<int,int>> vec;
	vector<pair<int,int>> tmp;
	vec.push_back({0, 0});

	for (auto x : blocks)
	{
		tmp.clear();
		for (int i = 0; i < vec.size(); ++i)
		{
			if (vec[i].first == vec[i].second && vec[i].first + x <= n)
			{
				tmp.push_back({vec[i].first + x, vec[i].second});
				continue;
			}

			if (vec[i].first + x <= n)
				tmp.push_back({vec[i].first + x, vec[i].second});
			if (vec[i].second + x <= n)
				tmp.push_back({vec[i].first, vec[i].second + x});
		}
		vec = tmp;
	}

	bool res = false;
	for (auto x : vec)
		res = (res || x == make_pair(n, n));

	cout << (res ? "YES\n" : "NO\n");
}

int main()
{
	int t;
	cin >> t;

	while (t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

int const N = 4e3 + 7;
int ar[N];

bool dp[N];
void solve()
{
	int n;
	cin >> n;

	for (int i = 0; i < 2*n; ++i)
		cin >> ar[i];

	vector<int> blocks;

	int mx = ar[0], ctr = 1;
	for (int i = 1; i <= 2*n; ++i)
	{
		if (mx < ar[i] || i == 2*n)
		{
			if (ctr != 0)
				blocks.push_back(ctr);
			ctr = 1;
			mx = ar[i];
		}
		else
		{
			ctr++;
		}
	}

	memset(dp, false, sizeof(dp));
	dp[0] = true;
	for (int i = 0; i < blocks.size(); ++i)
	{
		for (int j = N-1; j >= 0; --j)
		{
			dp[j] = (dp[j] || dp[j-blocks[i]]);
		}
	}

	cout << (dp[n] ? "YES\n" : "NO\n");
}

int main()
{
	int t;
	cin >> t;

	while (t--)
		solve();
	return 0;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<char,int> pci;

int t,n,pd[5000][5000],p[4040];
vector<int> v;

int solve(int pos,int sum){

	//cout << pos << " " << sum << "\n";

	if(sum < 0) return 0;
	if(sum == 0) return 1;
	if(pos >= v.size() && sum != 0) return 0;

	if(pd[pos][sum] != -1){
		return pd[pos][sum];
	}

	int coloca = solve(pos+1,sum-v[pos]);
	int ncoloca = solve(pos+1,sum);

	return pd[pos][sum] = max(coloca,ncoloca);
}

int main(){
	cin >> t;
	while(t--){
		memset(pd,-1,sizeof(pd));
		v.clear();
		cin >> n;
		for(int i=1;i<=2*n;i++){
			cin >> p[i];
		}

		int ma = 2*n,posa = 2*n;
		for(int i=2*n;i>=1;i--){
			if(p[i] == ma){
				v.push_back(posa-i+1);
				posa = i-1;
				ma--;
			}
		}

		if(posa != 0){
			v.push_back(posa-1+1);
		}

		/*for(auto it : v){
			cout << it << " ";
		}*/

		//cout << "\n";

		int resp = solve(0,n);

		//cout << resp << "\n";

		if(resp == 1){
			cout << "YES\n";
		}else{
			cout << "NO\n";
		}
	}
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<char,int> pci;

int t,n,pd[5000][5000],p[4040];
vector<int> v;

int main(){
	cin >> t;
	while(t--){

		v.clear();
		cin >> n;
		for(int i=1;i<=2*n;i++){
			cin >> p[i];
		}

		int ma = 2*n,posa = 2*n;
		for(int i=2*n;i>=1;i--){
			if(p[i] == ma){
				v.push_back(posa-i+1);
				posa = i-1;
				ma--;
			}
		}

		if(posa != 0){
			v.push_back(posa-1+1);
		}

		for(int i=0;i<=v.size();i++){
			pd[i][0] = 1;
		}

		for(int i=1;i<=n;i++){
			pd[0][i] = 0;
		}

		for(int i=1;i<=v.size();i++){
			for(int j=1;j<=n;j++){
				if(j < v[i-1]){
					pd[i][j] = pd[i-1][j];//ncoloca
				}else{
					pd[i][j] = pd[i - 1][j] || pd[i - 1][j - v[i - 1]]; // n ou coloca
				}
			}
		}

		//cout << resp << "\n";

		if(pd[v.size()][n] == 1){
			cout << "YES\n";
		}else{
			cout << "NO\n";
		}
	}
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<char,int> pci;

int t,n,pd[5000][5000],p[4040];
vector<int> v;

int main(){
	cin >> t;
	while(t--){

		v.clear();
		cin >> n;
		for(int i=1;i<=2*n;i++){
			cin >> p[i];
		}

		int ma = 2*n,posa = 2*n;
		for(int i=2*n;i>=1;i--){
			if(p[i] == ma){
				v.push_back(posa-i+1);
				posa = i-1;
				ma--;
			}
		}

		//if(posa != 0){
		//	v.push_back(posa-1+1);
		//}

		//for(auto it : v){
		//	cout << it << " ";
		//}

		//cout << "\n";

		for(int i=0;i<=v.size();i++){
			pd[i][0] = 1;
		}

		for(int i=1;i<=n;i++){
			pd[0][i] = 0;
		}

		for(int i=1;i<=v.size();i++){
			for(int j=1;j<=n;j++){
				if(j < v[i-1]){
					pd[i][j] = pd[i-1][j];//ncoloca
				}else{
					pd[i][j] = pd[i - 1][j] || pd[i - 1][j - v[i - 1]]; // n ou coloca
				}
			}
		}

		//cout << resp << "\n";

		if(pd[v.size()][n] == 1){
			cout << "YES\n";
		}else{
			cout << "NO\n";
		}
	}
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<char,int> pci;

int t,n,pd[5000][5000],p[4040];

int main(){
	cin >> t;
	while(t--){

		vector<int> v,aux;
		cin >> n;
		int ma =0;

		for(int i=1;i<=2*n;i++){
			cin >> p[i];
			if(p[i] > ma){
				aux.push_back(i);
				ma = p[i];
			}
		}

		for(int i=0;i<aux.size()-1;i++){
			//cout << aux[i+1] << " " << aux[i] << "\n";

			v.push_back(aux[i+1] - aux[i]);
		}

		v.push_back(((2*n)+1) - aux[aux.size()-1]);

		/*for(int i=0;i<v.size();i++){
			cout << v[i] << " ";
		}

		cout << "\n";
*/

		for(int i=0;i<=v.size();i++){
			pd[i][0] = 1;
		}

		for(int i=1;i<=n;i++){
			pd[0][i] = 0;
		}

		for(int i=1;i<=v.size();i++){
			for(int j=1;j<=n;j++){
				if(j < v[i-1]){
					pd[i][j] = pd[i-1][j];//ncoloca
				}else{
					pd[i][j] = (pd[i - 1][j] || pd[i - 1][j - v[i - 1]]); // n ou coloca
				}
			}
		}

				//cout << resp << "\n";

		if(pd[v.size()][n] == 1){
			cout << "YES\n";
		}else{
			cout << "NO\n";
		}
	}
}


%:pragma GCC optimize "-O3"
%:pragma GCC optimize("Ofast")
%:pragma GCC optimize("inline")
%:pragma GCC optimize("fast-math")
%:pragma GCC optimize("unroll-loops")
%:pragma GCC optimize("inline-functions")
%:pragma GCC optimize("no-stack-protector")
%:pragma GCC optimize("inline-small-functions")
%:pragma GCC optimize("inline-functions-called-once")
%:pragma GCC target("sse3","sse2","sse")
#include<bits/stdc++.h>
#define ll long long
#define heap priority_queue
using namespace std;
const ll maxn=4000+5,inf=9e17;
bool dp[maxn];
vector<ll> v;
ll a[maxn],t,n,maxi,len;
int main()
{
	cin>>t;
	while(t--)
	{
		cin>>n;
		for(int i=1;i<=2*n;i++)
			cin>>a[i];
		maxi=a[1];
		len=1;
		for(int i=2;i<=2*n;i++)
			if(a[i]<=maxi)
				++len;
			else
			{
				v.push_back(len);
				maxi=a[i];
				len=1;
			}
		v.push_back(len);
		dp[0]=1;
		for(auto x:v)
			for(int j=n;j>=x;j--)
				dp[j]|=dp[j-x];
		if(dp[n])
			cout<<"YES\n";
		else
			cout<<"NO\n";
		v.clear();
		for(int j=0;j<=2*n;j++)
			dp[j]=a[j]=0;
	}
	return 0;
}


%:pragma GCC optimize "-O3"
%:pragma GCC optimize("Ofast")
%:pragma GCC optimize("inline")
%:pragma GCC optimize("fast-math")
%:pragma GCC optimize("unroll-loops")
%:pragma GCC optimize("inline-functions")
%:pragma GCC optimize("no-stack-protector")
%:pragma GCC optimize("inline-small-functions")
%:pragma GCC optimize("inline-functions-called-once")
%:pragma GCC target("sse3","sse2","sse")
#include<bits/stdc++.h>
#define ll long long
#define heap priority_queue
using namespace std;
const ll maxn=4000+5,inf=9e17;
ll dp[maxn];
vector<ll> v;
ll a[maxn],t,n,maxi,len;
int main()
{
	cin>>t;
	while(t--)
	{
		cin>>n;
		for(int i=1;i<=2*n;i++)
			cin>>a[i];
		maxi=a[1];
		for(int i=2;i<=2*n;i++)
			if(a[i]<=maxi)
				++len;
			else
			{
				v.push_back(len);
				maxi=a[i];
				len=1;
			}
		v.push_back(len);
		sort(v.begin(),v.end());
		for(auto x:v)
			for(int j=n;j>=x;j--)
				dp[j]=dp[j-x]+x;
		if(dp[n]==n)
			cout<<"YES\n";
		else
			cout<<"NO\n";
		v.clear();
		for(int j=0;j<=2*n;j++)
			dp[j]=a[j]=0;
	}
	return 0;
}


%:pragma GCC optimize "-O3"
%:pragma GCC optimize("Ofast")
%:pragma GCC optimize("inline")
%:pragma GCC optimize("fast-math")
%:pragma GCC optimize("unroll-loops")
%:pragma GCC optimize("inline-functions")
%:pragma GCC optimize("no-stack-protector")
%:pragma GCC optimize("inline-small-functions")
%:pragma GCC optimize("inline-functions-called-once")
%:pragma GCC target("sse3","sse2","sse")
#include<bits/stdc++.h>
#define ll long long
#define heap priority_queue
using namespace std;
const ll maxn=4000+5,inf=9e17;
ll dp[maxn];
vector<ll> v;
ll a[maxn],t,n,maxi,len;
int main()
{
	cin>>t;
	while(t--)
	{
		cin>>n;
		for(int i=1;i<=2*n;i++)
			cin>>a[i];
		maxi=a[1];
		len=1;
		for(int i=2;i<=2*n;i++)
			if(a[i]<=maxi)
				++len;
			else
			{
				v.push_back(len);
				maxi=a[i];
				len=1;
			}
		v.push_back(len);
		sort(v.begin(),v.end());
		for(auto x:v)
			for(int j=n;j>=x;j--)
				dp[j]=dp[j-x]+x;
		if(dp[n]==n)
			cout<<"YES\n";
		else
			cout<<"NO\n";
		v.clear();
		for(int j=0;j<=2*n;j++)
			dp[j]=a[j]=0;
	}
	return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int t;cin>>t;
    while(t-->0){
        int n;cin>>n;
        int p[2*n];
        for(int i=0;i<2*n;i++) cin>>p[i];
        vector<int> v;
        int i=0;
        while(i<2*n){
            int cnt=1;
            int j=i+1;
            while(j<2*n && p[i]>p[j]){
                cnt++;
                j++;
            }
            i=j;
            v.push_back(cnt);
            //cout<<cnt<<" ";
        }
        cout<<endl;
        int size=v.size();
        bool dp[n+1][size+1];
        for(int i=0;i<=n;i++){
            for(int j=0;j<=size;j++){
                if(i==0 && j==0) dp[i][j]=true;
                else if(j==0) dp[i][j]=false;
                else if(i==0) dp[i][j]=true;
                else{
                    if(i-v[j-1]>=0){
                        dp[i][j]=dp[i-v[j-1]][j-1]||dp[i][j-1];
                    }
                    else dp[i][j]=dp[i][j-1];
                }
            }
        }
        if(dp[n][size]) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int t;cin>>t;
    while(t-->0){
        int n;cin>>n;
        int p[2*n];
        for(int i=0;i<2*n;i++) cin>>p[i];
        vector<int> v;
        int i=0;
        while(i<2*n){
            int cnt=1;
            while(i<2*n-1 && p[i]>p[i+1]){
                cnt++;
                i++;
            }
            i++;
            v.push_back(cnt);
        }
        int size=v.size();
        bool dp[n+1][size+1];
        for(int i=0;i<=n;i++){
            for(int j=0;j<=size;j++){
                if(i==0 && j==0) dp[i][j]=true;
                else if(j==0) dp[i][j]=false;
                else if(i==0) dp[i][j]=true;
                else{
                    if(i-v[j-1]>=0){
                        dp[i][j]=dp[i-v[j-1]][j-1]||dp[i][j-1];
                    }
                    else dp[i][j]=dp[i][j-1];
                }
            }
        }
        if(dp[n][size]) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int t;cin>>t;
    while(t-->0){
        int n;cin>>n;
        int p[2*n];
        for(int i=0;i<2*n;i++) cin>>p[i];
        vector<int> v;
        int i=0;
        while(i<2*n){
            int cnt=1;
            while(i<2*n-1 && p[i]>p[i+1]){
                cnt++;
                i++;
            }
            i++;
            v.push_back(cnt);
        }
        int size=v.size();
        bool dp[n+1][size+1];
        for(int i=0;i<=n;i++){
            for(int j=0;j<=size;j++){
                if(i==0 && j==0) dp[i][j]=true;
                else if(j==0) dp[i][j]=false;
                else if(i==0) dp[i][j]=true;
                else{
                    if(i-v[j-1]>=0){
                        dp[i][j]=dp[i-v[j-1]][j-1]||dp[i][j-1];
                    }
                    else dp[i][j]=dp[i][j-1];
                }
            }
        }
        if(dp[n][size]) System.out.println("YES");
        else System.out.println("NO");
    }
}


#include<bits/stdc++.h>
using namespace std;

int dp[2005];
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt","r",stdin);
#endif
    int nn,n;
    int a[2005],b[4005];
    scanf("%d",&nn);
    while(nn--){
        scanf("%d",&n);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<2*n;i++)scanf("%d",&a[i]);
        int cnt=0,p=1,k=a[0];
        for(int i=1;i<2*n;i++){
            if(a[i]>k){
                b[cnt++]=p;
                p=1;
                k=a[i];
            }
            else p++;
        }
        dp[0]=1;
        if(p)b[cnt++]=p;
        int sum=n*2;
        for(int i=0;i<cnt;i++){
            for(int j=sum;j>=0;j--){
                if(dp[j])dp[j+b[i]]=1;
            }
        }
        if(dp[n])printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int dp[4005];
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt","r",stdin);
#endif
    int nn,n;
    int a[4005],b[4005];
    scanf("%d",&nn);
    while(nn--){
        scanf("%d",&n);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<2*n;i++)scanf("%d",&a[i]);
        int cnt=0,p=1,k=a[0];
        for(int i=1;i<2*n;i++){
            if(a[i]>k){
                b[cnt++]=p;
                p=1;
                k=a[i];
            }
            else p++;
        }
        dp[0]=1;
        if(p)b[cnt++]=p;
        int sum=n*2;
        for(int i=0;i<cnt;i++){
            for(int j=sum;j>=0;j--){
                if(dp[j])dp[j+b[i]]=1;
            }
        }
        if(dp[n])printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int dp[2005];
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt","r",stdin);
#endif
    int nn,n;
    int a[2005],b[10005];
    scanf("%d",&nn);
    while(nn--){
        scanf("%d",&n);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<2*n;i++)scanf("%d",&a[i]);
        int cnt=0,p=1,k=a[0];
        for(int i=1;i<2*n;i++){
            if(a[i]>k){
                b[cnt++]=p;
                p=1;
                k=a[i];
            }
            else p++;
        }
        dp[0]=1;
        if(p)b[cnt++]=p;
        int sum=n*2;
        for(int i=0;i<cnt;i++){
            for(int j=sum;j>=0;j--){
                if(dp[j])dp[j+b[i]]=1;
            }
        }
        if(dp[n])printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

int dp[10005];
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt","r",stdin);
#endif
    int nn,n;
    int a[10005],b[10005];
    scanf("%d",&nn);
    while(nn--){
        scanf("%d",&n);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<2*n;i++)scanf("%d",&a[i]);
        int cnt=0,p=1,k=a[0];
        for(int i=1;i<2*n;i++){
            if(a[i]>k){
                b[cnt++]=p;
                p=1;
                k=a[i];
            }
            else p++;
        }
        dp[0]=1;
        if(p)b[cnt++]=p;
        int sum=n*2;
        for(int i=0;i<cnt;i++){
            for(int j=sum;j>=0;j--){
                if(dp[j])dp[j+b[i]]=1;
            }
        }
        if(dp[n])printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
int read()
{
	char x=getchar();int ans=0,flag=1;
	while(!isdigit(x)) if (x=='-') flag=-1,x=getchar();else x=getchar();
	while(isdigit(x)) ans=ans*10+x-'0',x=getchar();
	return ans*flag;
}
int n,a[2005],dp[2005];
vector<int> v;
signed main()
{
	int T=read();
	while(T--)
	{
		n=read();
		memset(dp,0,sizeof(dp));
		dp[0]=1;
		v.clear();
		for (int i=1;i<=2*n;i++)
			a[i]=read();
		for (int i=1;i<=2*n;i++)
		{
			int flag=-1;
			for (int j=1;j<=2*n;j++)
			{
				if (a[j]>i)
				{
					flag=0;
					break;
				}
				if (a[j]==i)
				{
					flag=j;
					break;
				}
			}
			if (!flag) continue;
			for (int j=flag;j<=2*n;j++)
			{
				if (a[j]>i)
				{
					v.push_back(j-flag);
					break;
				}
			}
		}
		for (int i=0;i<v.size();i++)
		{
			for (int j=n-v[i];j>=0;j--)
			{
				dp[j+v[i]]=max(dp[j+v[i]],dp[j]);
			}
		}
		if (dp[n]) puts("YES");
		else puts("NO");
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
int read()
{
	char x=getchar();int ans=0,flag=1;
	while(!isdigit(x)) if (x=='-') flag=-1,x=getchar();else x=getchar();
	while(isdigit(x)) ans=ans*10+x-'0',x=getchar();
	return ans*flag;
}
int n,a[4005],dp[4005];
vector<int> v;
signed main()
{
	int T=read();
	while(T--)
	{
		n=read();
		memset(dp,0,sizeof(dp));
		dp[0]=1;
		v.clear();
		for (int i=1;i<=2*n;i++)
			a[i]=read();
		for (int i=1;i<=2*n;i++)
		{
			int flag=-1;
			for (int j=1;j<=2*n;j++)
			{
				if (a[j]>i)
				{
					flag=0;
					break;
				}
				if (a[j]==i)
				{
					flag=j;
					break;
				}
			}
			if (!flag) continue;
			for (int j=flag;j<=2*n;j++)
			{
				if (a[j]>i)
				{
					v.push_back(j-flag);
					break;
				}
				if (j==2*n) v.push_back(2*n-flag+1);
			}
		}
		for (int i=0;i<v.size();i++)
		{
			if (v[i]>n)
			{
				break;
			}
			for (int j=n-v[i];j>=0;j--)
			{
				dp[j+v[i]]=max(dp[j+v[i]],dp[j]);
			}
		}
		if (dp[n]) puts("YES");
		else puts("NO");
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
int read()
{
	char x=getchar();int ans=0,flag=1;
	while(!isdigit(x)) if (x=='-') flag=-1,x=getchar();else x=getchar();
	while(isdigit(x)) ans=ans*10+x-'0',x=getchar();
	return ans*flag;
}
int n,a[2005],dp[2005];
vector<int> v;
signed main()
{
	int T=read();
	while(T--)
	{
		n=read();
		memset(dp,0,sizeof(dp));
		dp[0]=1;
		v.clear();
		for (int i=1;i<=2*n;i++)
			a[i]=read();
		for (int i=1;i<=2*n;i++)
		{
			int flag=-1;
			for (int j=1;j<=2*n;j++)
			{
				if (a[j]>i)
				{
					flag=0;
					break;
				}
				if (a[j]==i)
				{
					flag=j;
					break;
				}
			}
			if (!flag) continue;
			for (int j=flag;j<=2*n;j++)
			{
				if (a[j]>i)
				{
					v.push_back(j-flag);
					break;
				}
				if (j==2*n) v.push_back(2*n-flag+1);
			}
		}
		for (int i=0;i<v.size();i++)
		{
			if (v[i]>n)
			{
				break;
			}
			for (int j=n-v[i];j>=0;j--)
			{
				dp[j+v[i]]=max(dp[j+v[i]],dp[j]);
			}
		}
		if (dp[n]) puts("YES");
		else puts("NO");
	}
	return 0;
}