import java.util.Scanner;

public class Main
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		for(int i=0;i<t;i++)
		{
			int n=sc.nextInt();
			System.out.println(n);
			for(int j=1;j<=n;j++)
				System.out.print(j+" ");
			System.out.println();
		}
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		for(int i=0;i<t;i++)
		{
			int n=sc.nextInt();
			System.out.println(n-1);
			System.out.print(n+" ");
			for(int j=2;j<n;j++)
				System.out.print(j+" ");
			System.out.println();
		}
	}
}


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

public class Contest {

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

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

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

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

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time(ms) = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    class MyComparator implements Comparable<MyComparator> {

        int x;
        int y;

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

        @Override
        public int compareTo(MyComparator a) {
            if (x == a.x) {
                return (y - a.y);
            }
            return x - a.x;
        }
    }

    public static boolean isPrime(int num) {
        if (num > 2 && num % 2 == 0) {
            //System.out.println(num + " is not prime");
            return false;
        }
        int top = (int) Math.sqrt(num) + 1;
        for (int i = 3; i < top; i += 2) {
            if (num % i == 0) {
                //System.out.println(num + " is not prime");
                return false;
            }
        }
        //System.out.println(num + " is prime");
        return true;
    }

    private static long gcd(long a, long b) {
        BigInteger b1 = BigInteger.valueOf(a);
        BigInteger b2 = BigInteger.valueOf(b);
        BigInteger gcd = b1.gcd(b2);
        return gcd.longValue();
    }

    static int floorSqrt(int x) {
        // Base cases
        if (x == 0 || x == 1) {
            return x;
        }

        int i = 1, result = 1;

        while (result <= x) {
            i++;
            result = i * i;
        }

        return i;
    }

    public void solveE() throws IOException {

    }

    public void solveD() throws IOException {

    }

    public void solveC2() throws IOException {

    }

    public void solveС() throws IOException {

    }

    public void solveB() throws IOException {

    }

    public void solve() throws IOException {
        int t = readInt();
        for (int i = 0; i < t; i++) {
            int n = readInt();
            int m = n;
            System.out.println(m);
            StringBuilder builder = new StringBuilder();
            for(int j=n; j>0; j--) {
                builder.append(j).append(" ");
            }
            builder.setLength(builder.length()-1);
            System.out.println(builder);
        }
    }

}


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

public class Contest {

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

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

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

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

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time(ms) = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    class MyComparator implements Comparable<MyComparator> {

        int x;
        int y;

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

        @Override
        public int compareTo(MyComparator a) {
            if (x == a.x) {
                return (y - a.y);
            }
            return x - a.x;
        }
    }

    public static boolean isPrime(int num) {
        if (num > 2 && num % 2 == 0) {
            //System.out.println(num + " is not prime");
            return false;
        }
        int top = (int) Math.sqrt(num) + 1;
        for (int i = 3; i < top; i += 2) {
            if (num % i == 0) {
                //System.out.println(num + " is not prime");
                return false;
            }
        }
        //System.out.println(num + " is prime");
        return true;
    }

    private static long gcd(long a, long b) {
        BigInteger b1 = BigInteger.valueOf(a);
        BigInteger b2 = BigInteger.valueOf(b);
        BigInteger gcd = b1.gcd(b2);
        return gcd.longValue();
    }

    static int floorSqrt(int x) {
        // Base cases
        if (x == 0 || x == 1) {
            return x;
        }

        int i = 1, result = 1;

        while (result <= x) {
            i++;
            result = i * i;
        }

        return i;
    }

    public void solveE() throws IOException {

    }

    public void solveD() throws IOException {

    }

    public void solveC2() throws IOException {

    }

    public void solveС() throws IOException {

    }

    public void solveB() throws IOException {

    }

    public void solve() throws IOException {
        int t = readInt();
        for (int i = 0; i < t; i++) {
            int n = readInt();
            int m = n;
            System.out.println(m);
            StringBuilder builder = new StringBuilder();
            for(int j=1; j<=m; j++) {
                builder.append(j).append(" ");
            }
            builder.setLength(builder.length()-1);
            System.out.println(builder);
        }
    }

}


import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Codeforces {
	static String string;
	static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;

        // base case
        if (a == b)
            return a;

        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }
	static boolean ab(int i,HashSet<Integer> hs,int n,int prev)
	{
		if(i==n)
			return true;
		int cur=2;
		while(i<4*n)
		{
			if(prev==-1)
			{
				hs.add(cur);
				if(ab(i+1, hs, n, cur))
				{

					string=cur+" "+string;
					return true;
				}
				else
					hs.remove(hs.size()-1);
			}
			else {
				if(!hs.contains(cur)&&gcd(cur, prev)>1)
				{
					hs.add(cur);
					Iterator<Integer> iterator=hs.iterator();
					int flag=0;
					while(iterator.hasNext())
					{
						int x=iterator.next();
						if(x%cur==0||cur%x==0)
						{
							flag=1;
							break;
						}
					}

					if(flag==0&&ab(i+1, hs, n, cur))
					{
					string=cur+" "+string;
					return true;
					}
					hs.remove(hs.size()-1);
				}

			}
			cur+=2;
		}
		return false;
	}
	static int lcm(int a,int b)
	{
		for(int i=Math.min(a, b);i<=a*b;i++)
			if(i%a==0&&i%b==0)
				return i;
		return 0;
	}
public static void main(String[] args)throws IOException
{
	BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));

	int T=Integer.parseInt(bReader.readLine());

	while(T-->0)
	{

		string="";

		StringBuilder sBuilder=new StringBuilder();
		int n=Integer.parseInt(bReader.readLine()),co=0;
		for(int i=0;i<n;i++)
		{

				co++;
				string+=(1+i)+" ";

		}
		//String[] al=bReader.readLine().split(" ");
		System.out.println(n);
		System.out.println(string);

	}

}
}


import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Codeforces {
	static String string;
	static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;

        // base case
        if (a == b)
            return a;

        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }
	static boolean ab(int i,HashSet<Integer> hs,int n,int prev)
	{
		if(i==n)
			return true;
		int cur=2;
		while(i<4*n)
		{
			if(prev==-1)
			{
				hs.add(cur);
				if(ab(i+1, hs, n, cur))
				{

					string=cur+" "+string;
					return true;
				}
				else
					hs.remove(hs.size()-1);
			}
			else {
				if(!hs.contains(cur)&&gcd(cur, prev)>1)
				{
					hs.add(cur);
					Iterator<Integer> iterator=hs.iterator();
					int flag=0;
					while(iterator.hasNext())
					{
						int x=iterator.next();
						if(x%cur==0||cur%x==0)
						{
							flag=1;
							break;
						}
					}

					if(flag==0&&ab(i+1, hs, n, cur))
					{
					string=cur+" "+string;
					return true;
					}
					hs.remove(hs.size()-1);
				}

			}
			cur+=2;
		}
		return false;
	}
	static int lcm(int a,int b)
	{
		for(int i=Math.min(a, b);i<=a*b;i++)
			if(i%a==0&&i%b==0)
				return i;
		return 0;
	}
public static void main(String[] args)throws IOException
{
	BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));

	int T=Integer.parseInt(bReader.readLine());

	while(T-->0)
	{

		string="";

		StringBuilder sBuilder=new StringBuilder();
		int n=Integer.parseInt(bReader.readLine()),co=0;
		for(int i=0;i<n;i++)
		{

				co++;
				string+=(n-i)+" ";

		}
		//String[] al=bReader.readLine().split(" ");
		System.out.println(co);
		System.out.println(string);

	}

}
}


import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Codeforces {
	static String string;
	static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;

        // base case
        if (a == b)
            return a;

        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }
	static boolean ab(int i,HashSet<Integer> hs,int n,int prev)
	{
		if(i==n)
			return true;
		int cur=2;
		while(i<4*n)
		{
			if(prev==-1)
			{
				hs.add(cur);
				if(ab(i+1, hs, n, cur))
				{

					string=cur+" "+string;
					return true;
				}
				else
					hs.remove(hs.size()-1);
			}
			else {
				if(!hs.contains(cur)&&gcd(cur, prev)>1)
				{
					hs.add(cur);
					Iterator<Integer> iterator=hs.iterator();
					int flag=0;
					while(iterator.hasNext())
					{
						int x=iterator.next();
						if(x%cur==0||cur%x==0)
						{
							flag=1;
							break;
						}
					}

					if(flag==0&&ab(i+1, hs, n, cur))
					{
					string=cur+" "+string;
					return true;
					}
					hs.remove(hs.size()-1);
				}

			}
			cur+=2;
		}
		return false;
	}
	static int lcm(int a,int b)
	{
		for(int i=Math.min(a, b);i<=a*b;i++)
			if(i%a==0&&i%b==0)
				return i;
		return 0;
	}
public static void main(String[] args)throws IOException
{
	BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));

	int T=Integer.parseInt(bReader.readLine());

	while(T-->0)
	{

		string="";

		StringBuilder sBuilder=new StringBuilder();
		int n=Integer.parseInt(bReader.readLine()),co=0;
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n-i;j++)
			{
				string+=(n-i)+" ";
			}

		}
		//String[] al=bReader.readLine().split(" ");

		System.out.println(string);

	}

}
}


import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Codeforces {
	static String string;
	static int gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0)
          return b;
        if (b == 0)
          return a;

        // base case
        if (a == b)
            return a;

        // a is greater
        if (a > b)
            return gcd(a-b, b);
        return gcd(a, b-a);
    }
	static boolean ab(int i,HashSet<Integer> hs,int n,int prev)
	{
		if(i==n)
			return true;
		int cur=2;
		while(i<4*n)
		{
			if(prev==-1)
			{
				hs.add(cur);
				if(ab(i+1, hs, n, cur))
				{

					string=cur+" "+string;
					return true;
				}
				else
					hs.remove(hs.size()-1);
			}
			else {
				if(!hs.contains(cur)&&gcd(cur, prev)>1)
				{
					hs.add(cur);
					Iterator<Integer> iterator=hs.iterator();
					int flag=0;
					while(iterator.hasNext())
					{
						int x=iterator.next();
						if(x%cur==0||cur%x==0)
						{
							flag=1;
							break;
						}
					}

					if(flag==0&&ab(i+1, hs, n, cur))
					{
					string=cur+" "+string;
					return true;
					}
					hs.remove(hs.size()-1);
				}

			}
			cur+=2;
		}
		return false;
	}
	static int lcm(int a,int b)
	{
		for(int i=Math.min(a, b);i<=a*b;i++)
			if(i%a==0&&i%b==0)
				return i;
		return 0;
	}
public static void main(String[] args)throws IOException
{
	BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));

	int T=Integer.parseInt(bReader.readLine());

	while(T-->0)
	{

		string="";

		StringBuilder sBuilder=new StringBuilder();
		int n=Integer.parseInt(bReader.readLine()),co=0;
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n-i;j++)
			{
				co++;
				string+=(n-i)+" ";
			}

		}
		//String[] al=bReader.readLine().split(" ");
		System.out.println(co);
		System.out.println(string);

	}

}
}


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

public class codeforces {
	public static void main(String[] args) throws Exception {

		int t=sc.nextInt();
		while(t-->0) {
			int n=sc.nextInt();
			pw.println(n);
			for(int i=1;i<=n;i++) {
				pw.print(i+" ");
			}
			pw.println();
		}
		pw.close();
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(FileReader r) {
			br = new BufferedReader(r);
		}

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

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

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

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

		public double nextDouble() throws IOException {
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if (x.charAt(0) == '-') {
				neg = true;
				start++;
			}
			for (int i = start; i < x.length(); i++)
				if (x.charAt(i) == '.') {
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				} else {
					sb.append(x.charAt(i));
					if (dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg ? -1 : 1);
		}

		public long[] nextlongArray(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public Long[] nextLongArray(int n) throws IOException {
			Long[] a = new Long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] a = new Integer[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

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

	}

	static class pair implements Comparable<pair> {
		long x;
		long y;

		public pair(long x, long y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return x + " " + y;
		}

		public boolean equals(Object o) {
			if (o instanceof pair) {
				pair p = (pair) o;
				return p.x == x && p.y == y;
			}
			return false;
		}

		public int hashCode() {
			return new Double(x).hashCode() * 31 + new Double(y).hashCode();
		}

		public int compareTo(pair other) {
			if (this.x == other.x) {
				return Long.compare(this.y, other.y);
			}
			return Long.compare(this.x, other.x);
		}
	}

	static class tuble implements Comparable<tuble> {
		int x;
		int y;
		int z;

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

		public String toString() {
			return x + " " + y + " " + z;
		}

		public int compareTo(tuble other) {
			if (this.x == other.x) {
				if (this.y == other.y) {
					return this.z - other.z;
				}
				return this.y - other.y;
			} else {
				return this.x - other.x;
			}
		}
	}

	static long mod = 1000000007;
	static Random rn = new Random();
	static Scanner sc = new Scanner(System.in);
	static PrintWriter pw = new PrintWriter(System.out);
}


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

public class codeforces {
	public static void main(String[] args) throws Exception {

		int t=sc.nextInt();
		while(t-->0) {
			int n=sc.nextInt();
			pw.println(n);
			for(int i=n;i>0;i--) {
				pw.print(i+" ");
			}
			pw.println();
		}
		pw.close();
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(FileReader r) {
			br = new BufferedReader(r);
		}

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

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

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

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

		public double nextDouble() throws IOException {
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if (x.charAt(0) == '-') {
				neg = true;
				start++;
			}
			for (int i = start; i < x.length(); i++)
				if (x.charAt(i) == '.') {
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				} else {
					sb.append(x.charAt(i));
					if (dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg ? -1 : 1);
		}

		public long[] nextlongArray(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public Long[] nextLongArray(int n) throws IOException {
			Long[] a = new Long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] a = new Integer[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

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

	}

	static class pair implements Comparable<pair> {
		long x;
		long y;

		public pair(long x, long y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return x + " " + y;
		}

		public boolean equals(Object o) {
			if (o instanceof pair) {
				pair p = (pair) o;
				return p.x == x && p.y == y;
			}
			return false;
		}

		public int hashCode() {
			return new Double(x).hashCode() * 31 + new Double(y).hashCode();
		}

		public int compareTo(pair other) {
			if (this.x == other.x) {
				return Long.compare(this.y, other.y);
			}
			return Long.compare(this.x, other.x);
		}
	}

	static class tuble implements Comparable<tuble> {
		int x;
		int y;
		int z;

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

		public String toString() {
			return x + " " + y + " " + z;
		}

		public int compareTo(tuble other) {
			if (this.x == other.x) {
				if (this.y == other.y) {
					return this.z - other.z;
				}
				return this.y - other.y;
			} else {
				return this.x - other.x;
			}
		}
	}

	static long mod = 1000000007;
	static Random rn = new Random();
	static Scanner sc = new Scanner(System.in);
	static PrintWriter pw = new PrintWriter(System.out);
}


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

public class a {
	public static void main(String[] args) throws Exception {

		BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		StringTokenizer st = new StringTokenizer(f.readLine());

		int T = Integer.parseInt(st.nextToken());

		for (int t = 0; t < T; t++) {
			int n = Integer.parseInt(f.readLine());
			out.println(n);
			out.print(1);
			for (int i = 2; i <= n; i++) {
				out.print(" " + i);
			}
			out.println();
		}

		out.close();
	}
}


import java.util.*;
public class Main{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0){
            int n=sc.nextInt();
            for(int i=1;i<=n;i++){
                System.out.print(i);
            }
            System.out.println();
        }
    }
}


import java.util.*;
public class Main{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0){
            int n=sc.nextInt();
            System.out.println(n);
            for(int i=1;i<=n;i++){
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
}


#!/usr/bin/python2
# -*- coding: utf-8 -*-

import sys

def rl(proc=None):
    if proc is not None:
        return proc(sys.stdin.readline())
    else:
        return sys.stdin.readline().rstrip()

def srl(proc=None):
    if proc is not None:
        return map(proc, rl().split())
    else:
        return rl().split()

def solve(A, sa, S):
    r = 0
    reserve = sa % S
    while sa > reserve:
        left = sa - A[-1][1]
        if left >= reserve:
            r += A[-1][0] * A[-1][1]
            A.pop()
            sa = left
        else:
            need = reserve - left
            r += (A[-1][1] - need) * A[-1][0]
            A[-1][1] = need
            sa = reserve
    return r

def main():
    N, S = srl(int)
    A = []
    B = []
    sa = 0
    sb = 0
    r = 0
    for _ in xrange(N):
        s, a, b = srl(int)
        if a >= b:
            A.append([a-b, s])
            r += b * s
            sa += s
        else:
            B.append([b-a, s])
            r += a * s
            sb += s
    A.sort()
    B.sort()
    r += solve(A, sa, S)
    r += solve(B, sb, S)
    ss = sum(x[1] for x in A) + sum(x[1] for x in B)
    if ss > S:
        r += sum(x * y for x, y in A) + sum(x * y for x, y in B)
    else:
        r += max(sum(x * y for x, y in A), sum(x * y for x, y in B))
    print(r)

if __name__ == '__main__':
    main()


from sys import stdin
from itertools import repeat
def get(p, k):
    res = 0
    for d, s in p:
        t = k if s > k else s
        res += d * t
        k -= t
    return res

def main():
    n, S = map(int, stdin.readline().split())
    dat = map(int, stdin.read().split(), repeat(10, 3 * n))
    ss = h = 0
    j = 0
    po = [[], [], []]
    cn = [0] * 3
    for i in xrange(n):
        s, a, b = dat[j:j+3]
        ss += s
        sgn = cmp(a, b)
        po[sgn].append(((a - b) * sgn, s))
        cn[sgn] += s
        h += ((a, a, b)[sgn]) * s
        j += 3
    po[1].sort()
    po[-1].sort()
    t = (ss + S - 1) / S
    r = t * S - ss
    if cn[1] % S + cn[0] + r < S:
        x = get(po[1], cn[1] % S)
        y = get(po[-1], cn[-1] % S)
        h -= min(x, y)
    print h
main()


from sys import stdin
from itertools import repeat
def get(p, k):
    res = 0
    for d, s in p:
        t = k if s > k else s
        res += d * t
        k -= t
    return res

def main():
    n, S = map(int, stdin.readline().split())
    dat = map(int, stdin.read().split(), repeat(10, 3 * n))
    ss = h = 0
    j = 0
    po = [[], [], []]
    cn = [0] * 3
    for i in xrange(n):
        s, a, b = dat[j:j+3]
        ss += s
        sgn = cmp(a, b)
        po[sgn].append(((a - b) * sgn, s))
        cn[sgn] += s
        h += ((a, a, b)[sgn]) * s
        j += 3
    po[1].sort()
    po[-1].sort()
    t = (ss + S - 1) / S
    r = t * S - ss
    if cn[0] + r < S:
        x = get(po[1], cn[1] % S)
        y = get(po[-1], cn[-1] % S)
        h -= min(x, y)
    print h
main()


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type person struct {
	s, a, b int64
}

type byDiff []person

func (s byDiff) Len() int           { return len(s) }
func (s byDiff) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byDiff) Less(i, j int) bool { return s[i].b-s[i].a < s[j].b-s[j].a }

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	s := readInt()
	totSlices := int64(0)
	ps := make([]person, n)
	for i := range ps {
		ps[i].s = readInt()
		ps[i].a = readInt()
		ps[i].b = readInt()
		totSlices += ps[i].s
	}
	sort.Sort(byDiff(ps))
	pizzas := (totSlices + s - 1) / s
	_, ans := ternarySearchMax(pizzas, func(a int64) int64 {
		var res int64
		b := pizzas - a
		a *= s
		b *= s
		for _, p := range ps {
			if p.a >= p.b {
				eat := p.s
				if a < p.s {
					eat = a
				}
				left := p.s - eat
				res += eat * p.a
				a -= eat
				if left > 0 {
					res += left * p.b
					b -= left
				}
			} else {
				eat := p.s
				if b < p.s {
					eat = b
				}
				left := p.s - eat
				res += eat * p.b
				b -= eat
				if left > 0 {
					res += left * p.a
					a -= left
				}
			}
		}
		return res
	})
	fmt.Println(ans)
}

func ternarySearchMax(hi int64, f func(int64) int64) (pos, val int64) {
	lo := int64(0)
	for hi-lo > 10 {
		m1 := lo + (hi-lo)/3
		m2 := hi - (hi-lo)/3
		if f(m1) < f(m2) {
			lo = m1
		} else {
			hi = m2 - 1
		}
	}
	m := f(lo)
	mx := lo
	for x := lo + 1; x <= hi; x++ {
		if y := f(x); y > m {
			m = y
			mx = x
		}
	}
	return mx, m
}


package main

import (
	"bufio"
	"fmt"
	"os"

	"golang.org/go/src/sort"
)

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type person struct {
	s, a, b int64
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	s := readInt()
	totSlices := int64(0)
	ps := make([]person, n)
	for i := range ps {
		ps[i].s = readInt()
		ps[i].a = readInt()
		ps[i].b = readInt()
		totSlices += ps[i].s
	}
	sort.Slice(ps, func(i, j int) bool { return ps[i].b-ps[i].a < ps[j].b-ps[j].a })
	pizzas := (totSlices + s - 1) / s
	_, ans := ternarySearchMax(pizzas, func(a int64) int64 {
		var res int64
		b := pizzas - a
		a *= s
		b *= s
		for _, p := range ps {
			if p.a >= p.b {
				eat := p.s
				if a < p.s {
					eat = a
				}
				left := p.s - eat
				res += eat * p.a
				a -= eat
				if left > 0 {
					res += left * p.b
					b -= left
				}
			} else {
				eat := p.s
				if b < p.s {
					eat = b
				}
				left := p.s - eat
				res += eat * p.b
				b -= eat
				if left > 0 {
					res += left * p.a
					a -= left
				}
			}
		}
		return res
	})
	fmt.Println(ans)
}

func ternarySearchMax(hi int64, f func(int64) int64) (pos, val int64) {
	lo := int64(0)
	for hi-lo > 10 {
		m1 := lo + (hi-lo)/3
		m2 := hi - (hi-lo)/3
		if f(m1) < f(m2) {
			lo = m1
		} else {
			hi = m2 - 1
		}
	}
	m := f(lo)
	mx := lo
	for x := lo + 1; x <= hi; x++ {
		if y := f(x); y > m {
			m = y
			mx = x
		}
	}
	return mx, m
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

var in = bufio.NewScanner(os.Stdin)

func readInt() int64 {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int64(0)
	for _, b := range in.Bytes() {
		res = res*10 + int64(b-'0')
	}
	return res
}

type person struct {
	s, a, b int64
}

type byDiff []person

func (s byDiff) Len() int           { return len(s) }
func (s byDiff) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s byDiff) Less(i, j int) bool {
	di := s[i].b - s[i].a
	if di < 0 {
		di *= -1
	}
	dj := s[j].b - s[j].a
	if dj < 0 {
		dj *= -1
	}
	return di > dj
}

func main() {
	in.Split(bufio.ScanWords)

	n := readInt()
	s := readInt()
	totSlices := int64(0)
	ps := make([]person, n)
	for i := range ps {
		ps[i].s = readInt()
		ps[i].a = readInt()
		ps[i].b = readInt()
		totSlices += ps[i].s
	}
	sort.Sort(byDiff(ps))
	pizzas := (totSlices + s - 1) / s
	_, ans := ternarySearchMax(pizzas, func(a int64) int64 {
		var res int64
		b := pizzas - a
		a *= s
		b *= s
		for _, p := range ps {
			if p.a >= p.b {
				eat := p.s
				if a < p.s {
					eat = a
				}
				left := p.s - eat
				res += eat * p.a
				a -= eat
				if left > 0 {
					res += left * p.b
					b -= left
				}
			} else {
				eat := p.s
				if b < p.s {
					eat = b
				}
				left := p.s - eat
				res += eat * p.b
				b -= eat
				if left > 0 {
					res += left * p.a
					a -= left
				}
			}
		}
		return res
	})
	fmt.Println(ans)
}

func ternarySearchMax(hi int64, f func(int64) int64) (pos, val int64) {
	lo := int64(0)
	for hi-lo > 10 {
		m1 := lo + (hi-lo)/3
		m2 := hi - (hi-lo)/3
		if f(m1) < f(m2) {
			lo = m1
		} else {
			hi = m2 - 1
		}
	}
	m := f(lo)
	mx := lo
	for x := lo + 1; x <= hi; x++ {
		if y := f(x); y > m {
			m = y
			mx = x
		}
	}
	return mx, m
}


from sys import stdin
from itertools import repeat
def get(p, k):
    res = 0
    for d, s in p:
        t = k if s > k else s
        res += d * t
        k -= t
    return res
def main():
    n, S = map(int, stdin.readline().split())
    dat = map(int, stdin.read().split(), repeat(10, 3 * n))
    ss = h = 0
    j = 0
    po = [[], [], []]
    cn = [0] * 3
    for i in xrange(n):
        s, a, b = dat[j:j+3]
        ss += s
        sgn = cmp(a, b)
        po[sgn].append(((a - b) * sgn, s))
        cn[sgn] += s
        h += ((a, a, b)[sgn]) * s
        j += 3
    po[1].sort()
    po[-1].sort()
    t = (ss + S - 1) / S
    r = t * S - ss
    if cn[1] % S + cn[0] + r < S:
        x = get(po[1], cn[1] % S)
        y = get(po[-1], cn[-1] % S)
        h -= min(x, y)
    print(h)
main()


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LL long long
#define uLL unsigned long long
#define uL unsigned long
#define uC unsigned char

#define NODES 1000007
#define NNNN 1000007
#define MemoryStackTotal 100000000
#define error 1e-8
long num[NNNN],A[NNNN],B[NNNN],C[NNNN],pa[NNNN],pb[NNNN];

static unsigned char BakaMemoryStack[MemoryStackTotal];static unsigned char *MemoryStackTop=BakaMemoryStack;void *Allocates(unsigned long size){MemoryStackTop+=size;return MemoryStackTop-size;}void Releases(unsigned long size){MemoryStackTop-=size;if (MemoryStackTop<BakaMemoryStack) {MemoryStackTop=BakaMemoryStack;}}
void mergesort(long *ds,int (*compare)(long a,long b),long size){long i,j,k,s,b,e;long *ms=(long*)Allocates(sizeof(long)*(size+1));	for (k=1;k<=size;k=k<<1)	{		for (i=1;i+k<=size;i+=k<<1)		{			s=i;b=i+k;e=b+k-1;			if (e>size) {e=size;}			for (j=1;(s<i+k)&&(b<=e);j++)			{				if (compare(ds[s],ds[b])<=0)				{					ms[j]=ds[s++];				}				else				{					ms[j]=ds[b++];				}			}			for (b=i+k-1;b>=s;b--)			{				ds[e--]=ds[b];			}			for (b=1;b<j;b++)			{				ds[i+b-1]=ms[b];			}		}	}	Releases(sizeof(long)*(size+1));}
int compare(long a,long b)
{
	return C[a]>C[b];
}
int main()
{
//	freopen("in.in","r",stdin);
	long a,b,c,i,j,k,upper,n,s;
	LL ans,ans1,ans2;
	scanf("%ld %ld",&n,&s);
	a=0;
	for (i=1;i<=n;i++)
	{
		scanf("%ld %ld %ld",&num[i],&A[i],&B[i]);
		a+=num[i];
	}
	upper=(a-1)/s+1;
	a=0;b=0;ans=0;
	*pa=0;*pb=0;
	for (i=1;i<=n;i++)
	{
		if (A[i]>B[i])
		{
			pa[++(*pa)]=i;
			a+=num[i];
			ans+=((LL)num[i]*A[i]);
			C[i]=A[i]-B[i];
		}
		else
		{
			pb[++(*pb)]=i;
			b+=num[i];
			ans+=((LL)num[i]*B[i]);
			C[i]=B[i]-A[i];
		}
	}
//	printf("%lld\n",ans);
	mergesort(pa,&compare,*pa);
	mergesort(pb,&compare,*pb);
	c=a/s+(a%s>0)+b/s+(b%s>0);
	if (c>upper)
	{
		a=a%s;b=b%s;
//		printf("%ld %ld\n",a,b);
		ans1=0;
		for (i=1;i<=*pa;i++)
		{
			if (a>num[pa[i]])
			{
				a-=num[pa[i]];
				ans1+=(LL)num[pa[i]]*C[pa[i]];
			}
			else
			{
				ans1+=(LL)a*C[pa[i]];
				a=0;
			}
		}
		ans2=0;
		for (i=1;i<=*pb;i++)
		{
			if (b>num[pb[i]])
			{
				b-=num[pb[i]];
				ans2+=(LL)num[pb[i]]*C[pb[i]];
			}
			else
			{
				ans2+=(LL)b*C[pb[i]];
				b=0;
			}
		}
//		printf("%lld %lld\n",ans1,ans2);
		if (ans2<ans1) {ans1=ans2;}
	}
	ans-=ans1;
	printf("%lld\n",ans);
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LL long long
#define uLL unsigned long long
#define uL unsigned long
#define uC unsigned char

#define NODES 1000007
#define NNNN 1000007
#define MemoryStackTotal 100000000
#define error 1e-8
long num[NNNN],A[NNNN],B[NNNN],C[NNNN],pa[NNNN],pb[NNNN];

static unsigned char BakaMemoryStack[MemoryStackTotal];static unsigned char *MemoryStackTop=BakaMemoryStack;void *Allocates(unsigned long size){MemoryStackTop+=size;return MemoryStackTop-size;}void Releases(unsigned long size){MemoryStackTop-=size;if (MemoryStackTop<BakaMemoryStack) {MemoryStackTop=BakaMemoryStack;}}
void mergesort(long *ds,int (*compare)(long a,long b),long size){long i,j,k,s,b,e;long *ms=(long*)Allocates(sizeof(long)*(size+1));	for (k=1;k<=size;k=k<<1)	{		for (i=1;i+k<=size;i+=k<<1)		{			s=i;b=i+k;e=b+k-1;			if (e>size) {e=size;}			for (j=1;(s<i+k)&&(b<=e);j++)			{				if (compare(ds[s],ds[b])<=0)				{					ms[j]=ds[s++];				}				else				{					ms[j]=ds[b++];				}			}			for (b=i+k-1;b>=s;b--)			{				ds[e--]=ds[b];			}			for (b=1;b<j;b++)			{				ds[i+b-1]=ms[b];			}		}	}	Releases(sizeof(long)*(size+1));}
int compare(long a,long b)
{
	return C[a]>C[b];
}
int main()
{
//	freopen("in.in","r",stdin);
	long a,b,c,i,j,k,upper,n,s;
	LL ans,ans1,ans2;
	scanf("%ld %ld",&n,&s);
	a=0;
	for (i=1;i<=n;i++)
	{
		scanf("%ld %ld %ld",&num[i],&A[i],&B[i]);
		a+=num[i];
	}
	upper=(a-1)/s+1;
	a=0;b=0;ans=0;
	*pa=0;*pb=0;
	for (i=1;i<=n;i++)
	{
		if (A[i]>B[i])
		{
			pa[++(*pa)]=i;
			a+=num[i];
			ans+=((LL)num[i]*A[i]);
			C[i]=A[i]-B[i];
		}
		else
		{
			pb[++(*pb)]=i;
			b+=num[i];
			ans+=((LL)num[i]*B[i]);
			C[i]=B[i]-A[i];
		}
	}
//	printf("%lld\n",ans);
	mergesort(pa,&compare,*pa);
	mergesort(pb,&compare,*pb);
	c=a/s+((a%s)>0)+b/s+((b%s)>0);
	if (c>upper)
	{
		a=a%s;b=b%s;
//		printf("%ld %ld\n",a,b);
		ans1=0;
		for (i=1;i<=*pa;i++)
		{
			if (a>num[pa[i]])
			{
				a-=num[pa[i]];
				ans1+=(LL)num[pa[i]]*C[pa[i]];
			}
			else
			{
				ans1+=(LL)a*C[pa[i]];
				a=0;
				break;
			}
		}
		ans2=0;
		for (i=1;i<=*pb;i++)
		{
			if (b>num[pb[i]])
			{
				b-=num[pb[i]];
				ans2+=(LL)num[pb[i]]*C[pb[i]];
			}
			else
			{
				ans2+=(LL)b*C[pb[i]];
				b=0;
				break;
			}
		}
//		printf("%lld %lld\n",ans1,ans2);
		if (ans2<ans1) {ans1=ans2;}
		ans-=ans1;
	}
	printf("%lld\n",ans);
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LL long long
#define uLL unsigned long long
#define uL unsigned long
#define uC unsigned char

#define NODES 1000007
#define NNNN 1000007
#define MemoryStackTotal 10000000
#define error 1e-8
long num[NNNN],A[NNNN],B[NNNN],C[NNNN],pa[NNNN],pb[NNNN];

static unsigned char BakaMemoryStack[MemoryStackTotal];static unsigned char *MemoryStackTop=BakaMemoryStack;void *Allocates(unsigned long size){MemoryStackTop+=size;return MemoryStackTop-size;}void Releases(unsigned long size){MemoryStackTop-=size;if (MemoryStackTop<BakaMemoryStack) {MemoryStackTop=BakaMemoryStack;}}
void mergesort(long *ds,int (*compare)(long a,long b),long size){long i,j,k,s,b,e;long *ms=(long*)Allocates(sizeof(long)*(size+1));	for (k=1;k<=size;k=k<<1)	{		for (i=1;i+k<=size;i+=k<<1)		{			s=i;b=i+k;e=b+k-1;			if (e>size) {e=size;}			for (j=1;(s<i+k)&&(b<=e);j++)			{				if (compare(ds[s],ds[b])<=0)				{					ms[j]=ds[s++];				}				else				{					ms[j]=ds[b++];				}			}			for (b=i+k-1;b>=s;b--)			{				ds[e--]=ds[b];			}			for (b=1;b<j;b++)			{				ds[i+b-1]=ms[b];			}		}	}	Releases(sizeof(long)*(size+1));}
int compare(long a,long b)
{
	return C[a]>C[b];
}
int main()
{
	freopen("in.in","r",stdin);
	long a,b,c,i,j,k,upper,n,s;
	LL ans,ans1,ans2;
	scanf("%ld %ld",&n,&s);
	a=0;
	for (i=1;i<=n;i++)
	{
		scanf("%ld %ld %ld",&num[i],&A[i],&B[i]);
		a+=num[i];
	}
	upper=(a-1)/s+1;
	a=0;b=0;ans=0;
	*pa=0;*pb=0;
	for (i=1;i<=n;i++)
	{
		if (A[i]>B[i])
		{
			pa[++(*pa)]=i;
			a+=num[i];
			ans+=((LL)num[i]*A[i]);
			C[i]=A[i]-B[i];
		}
		else
		{
			pb[++(*pb)]=i;
			b+=num[i];
			ans+=((LL)num[i]*B[i]);
			C[i]=B[i]-A[i];
		}
	}
//	printf("%lld\n",ans);
	mergesort(pa,&compare,*pa);
	mergesort(pb,&compare,*pb);
	c=a/s+(a%s>0)+b/s+(b%s>0);
	if (c>upper)
	{
		a=a%s;b=b%s;
//		printf("%ld %ld\n",a,b);
		ans1=0;
		for (i=1;i<=*pa;i++)
		{
			if (a>num[pa[i]])
			{
				a-=num[pa[i]];
				ans1+=(LL)num[pa[i]]*C[pa[i]];
			}
			else
			{
				ans1+=(LL)a*C[pa[i]];
				a=0;
			}
		}
		ans2=0;
		for (i=1;i<=*pb;i++)
		{
			if (b>num[pb[i]])
			{
				b-=num[pb[i]];
				ans2+=(LL)num[pb[i]]*C[pb[i]];
			}
			else
			{
				ans2+=(LL)b*C[pb[i]];
				b=0;
			}
		}
//		printf("%lld %lld\n",ans1,ans2);
		if (ans2<ans1) {ans1=ans2;}
	}
	ans-=ans1;
	printf("%lld\n",ans);
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LL long long
#define uLL unsigned long long
#define uL unsigned long
#define uC unsigned char

#define NODES 1000007
#define NNNN 1000007
#define MemoryStackTotal 100000000
#define error 1e-8
long num[NNNN],A[NNNN],B[NNNN],C[NNNN],pa[NNNN],pb[NNNN];

static unsigned char BakaMemoryStack[MemoryStackTotal];static unsigned char *MemoryStackTop=BakaMemoryStack;void *Allocates(unsigned long size){MemoryStackTop+=size;return MemoryStackTop-size;}void Releases(unsigned long size){MemoryStackTop-=size;if (MemoryStackTop<BakaMemoryStack) {MemoryStackTop=BakaMemoryStack;}}
void mergesort(long *ds,int (*compare)(long a,long b),long size){long i,j,k,s,b,e;long *ms=(long*)Allocates(sizeof(long)*(size+1));	for (k=1;k<=size;k=k<<1)	{		for (i=1;i+k<=size;i+=k<<1)		{			s=i;b=i+k;e=b+k-1;			if (e>size) {e=size;}			for (j=1;(s<i+k)&&(b<=e);j++)			{				if (compare(ds[s],ds[b])<=0)				{					ms[j]=ds[s++];				}				else				{					ms[j]=ds[b++];				}			}			for (b=i+k-1;b>=s;b--)			{				ds[e--]=ds[b];			}			for (b=1;b<j;b++)			{				ds[i+b-1]=ms[b];			}		}	}	Releases(sizeof(long)*(size+1));}
int compare(long a,long b)
{
	return C[a]>C[b];
}
int main()
{
//	freopen("in.in","r",stdin);
	long a,b,c,i,j,k,upper,n,s;
	LL ans,ans1,ans2;
	scanf("%ld %ld",&n,&s);
	a=0;
	for (i=1;i<=n;i++)
	{
		scanf("%ld %ld %ld",&num[i],&A[i],&B[i]);
		a+=num[i];
	}
	upper=(a-1)/s+1;
	a=0;b=0;ans=0;
	*pa=0;*pb=0;
	for (i=1;i<=n;i++)
	{
		if (A[i]>B[i])
		{
			pa[++(*pa)]=i;
			a+=num[i];
			ans+=((LL)num[i]*A[i]);
			C[i]=A[i]-B[i];
		}
		else
		{
			pb[++(*pb)]=i;
			b+=num[i];
			ans+=((LL)num[i]*B[i]);
			C[i]=B[i]-A[i];
		}
	}
//	printf("%lld\n",ans);
	mergesort(pa,&compare,*pa);
	mergesort(pb,&compare,*pb);
	c=a/s+(a%s>0)+b/s+(b%s>0);
	if (c>upper)
	{
		a=a%s;b=b%s;
//		printf("%ld %ld\n",a,b);
		ans1=0;
		for (i=1;i<=*pa;i++)
		{
			if (a>num[pa[i]])
			{
				a-=num[pa[i]];
				ans1+=(LL)num[pa[i]]*C[pa[i]];
			}
			else
			{
				ans1+=(LL)a*C[pa[i]];
				a=0;
				break;
			}
		}
		ans2=0;
		for (i=1;i<=*pb;i++)
		{
			if (b>num[pb[i]])
			{
				b-=num[pb[i]];
				ans2+=(LL)num[pb[i]]*C[pb[i]];
			}
			else
			{
				ans2+=(LL)b*C[pb[i]];
				b=0;
				break;
			}
		}
//		printf("%lld %lld\n",ans1,ans2);
		if (ans2<ans1) {ans1=ans2;}
	}
	ans-=ans1;
	printf("%lld\n",ans);
	return 0;
}


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LL long long
#define uLL unsigned long long
#define uL unsigned long
#define uC unsigned char

#define NODES 1000007
#define NNNN 1000007
#define MemoryStackTotal 100000000
#define error 1e-8
LL num[NNNN],A[NNNN],B[NNNN],C[NNNN],pa[NNNN],pb[NNNN];

static unsigned char BakaMemoryStack[MemoryStackTotal];static unsigned char *MemoryStackTop=BakaMemoryStack;void *Allocates(unsigned LL size){MemoryStackTop+=size;return MemoryStackTop-size;}void Releases(unsigned LL size){MemoryStackTop-=size;if (MemoryStackTop<BakaMemoryStack) {MemoryStackTop=BakaMemoryStack;}}
void mergesort(LL *ds,int (*compare)(LL a,LL b),LL size){LL i,j,k,s,b,e;LL *ms=(LL*)Allocates(sizeof(LL)*(size+1));	for (k=1;k<=size;k=k<<1)	{		for (i=1;i+k<=size;i+=k<<1)		{			s=i;b=i+k;e=b+k-1;			if (e>size) {e=size;}			for (j=1;(s<i+k)&&(b<=e);j++)			{				if (compare(ds[s],ds[b])<=0)				{					ms[j]=ds[s++];				}				else				{					ms[j]=ds[b++];				}			}			for (b=i+k-1;b>=s;b--)			{				ds[e--]=ds[b];			}			for (b=1;b<j;b++)			{				ds[i+b-1]=ms[b];			}		}	}	Releases(sizeof(LL)*(size+1));}
int compare(LL a,LL b)
{
	return C[a]>C[b];
}

int main()
{
//	freopen("in.in","r",stdin);
	LL a,b,c,i,j,k,upper,n,s;
	LL ans,ans1,ans2;
	scanf("%lld %lld",&n,&s);
	a=0;
	for (i=1;i<=n;i++)
	{
		scanf("%lld %lld %lld",&num[i],&A[i],&B[i]);
		a+=num[i];
	}
	upper=(a-1)/s+1;
	a=0;b=0;ans=0;
	*pa=0;*pb=0;
	for (i=1;i<=n;i++)
	{
		if (A[i]>B[i])
		{
			pa[++(*pa)]=i;
			a+=num[i];
			ans+=((LL)num[i]*A[i]);
			C[i]=A[i]-B[i];
		}
		else
		{
			pb[++(*pb)]=i;
			b+=num[i];
			ans+=((LL)num[i]*B[i]);
			C[i]=B[i]-A[i];
		}
	}
//	printf("%lld\n",ans);
	mergesort(pa,&compare,*pa);
	mergesort(pb,&compare,*pb);
//	debug(n);
	c=a/s+((a%s)>0)+b/s+((b%s)>0);
//	printf("%ld %ld\n",c,upper);
	if (c>upper)
	{
		a=a%s;b=b%s;
//		printf("%ld %ld\n",a,b);
		ans1=0;
		for (i=1;a>0;i++)
		{
			if (a>num[pa[i]])
			{
				a-=num[pa[i]];
				ans1+=(LL)num[pa[i]]*C[pa[i]];
			}
			else
			{
				ans1+=(LL)a*C[pa[i]];
				a=0;
			}
		}
		ans2=0;
		for (i=1;b>0;i++)
		{
			if (b>num[pb[i]])
			{
				b-=num[pb[i]];
				ans2+=(LL)num[pb[i]]*C[pb[i]];
			}
			else
			{
				ans2+=(LL)b*C[pb[i]];
				b=0;
			}
		}
//		printf("%lld %lld\n",ans1,ans2);
		if (ans2<ans1) {ans1=ans2;}
		ans-=ans1;
	}
	printf("%lld\n",ans);
	return 0;
}


import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Collections.*;

import java.util.*;

public class B {

	public B () {
		int N = sc.nextInt();
		long S = sc.nextLong();
		long [][] Z = sc.nextLongs(N);

		long T = 0;
		for (int i : rep(N))
			T += Z[i][0];
		long P = ceil(T, S);

		List<long[]> LA = new ArrayList<>(), LB = new ArrayList<>();
		for (int i : rep(N)) {
			long D = Z[i][1] - Z[i][2];
			if (D > 0) LA.add(new long [] { Z[i][0], D });
			if (D < 0) LB.add(new long [] { Z[i][0], -D });
		}
		sort(LA, reverseOrder(by(1)));
		sort(LB, reverseOrder(by(1)));

		long res = 0;
		for (int i : rep(N))
			res += Z[i][0] * min(Z[i][1], Z[i][2]);
		for (long [] a : LA) {
			long d = a[0] - a[0]%S; a[0] %= S;
			res += d * a[1]; P -= d/S;
		}
		for (long [] b : LB) {
			long d = b[0] - b[0]%S; b[0] %= S;
			res += d * b[1]; P -= d/S;
		}

		Queue<long []> QA = new LinkedList<>(), QB = new LinkedList<>();
		QA.addAll(LA); QB.addAll(LB);

		long [] RA = new long [(int)P+1], RB = new long [(int)P+1];
		for (int n : req(1, (int)P)) {
			{
				long A = S; RA[n] = RA[n-1];
				while (A > 0 && !QA.isEmpty()) {
					long [] a = QA.peek();
					if (a[0] <= A) {
						RA[n] += a[0] * a[1];
						QA.poll(); A -= a[0];
					}
					else {
						RA[n] += A * a[1];
						a[0] -= A; A = 0;
					}
				}
			}

			{
				long B = S; RB[n] = RB[n-1];
				while (B > 0 && !QB.isEmpty()) {
					long [] b = QB.peek();
					if (b[0] <= B) {
						RB[n] += b[0] * b[1];
						QB.poll(); B -= b[0];
					}
					else {
						RB[n] += B * b[1];
						b[0] -= B; B = 0;
					}
				}
			}
		}

		long R = 0;
		for (int n : req(0, (int)P))
			R = max(R, RA[n] + RB[(int)P-n]);
		res += R;

		exit(res);
	}

	private static Comparator<long[]> by(final int ... J) { return new Comparator<long[]>() { public int compare(long[] x, long[] y) { for (int i : J) if (x[i] != y[i]) return Long.signum(x[i] - y[i]); return 0; }}; }
	private static long ceil (long p, long q) { return fc(p, q, true); }
	private static long fc(long p, long q, boolean up) {
		if (up) {
			if (q < 0) return fc(-p, -q, true);
			else if (p < 0) return -fc(-p, q, false);
			else return (p + q - 1) / q;
		} else if (q < 0) return fc(-p, -q, false);
		else if (p < 0) return -fc(-p, q, true);
		else return p / q;
	}
	private static int [] rep(int N) { return rep(0, N); }
	private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
	private static int [] req(int S, int T) { return rep(S, T+1); }
	////////////////////////////////////////////////////////////////////////////////////
	private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
	private static class IOUtils {
		public static class MyScanner {
			public String next() { newLine(); return line[index++]; }
			public int nextInt() { return Integer.parseInt(next()); }
			public long nextLong() { return Long.parseLong(next()); }
			public String nextLine() { line = null; return readLine(); }
			public String [] nextStrings() { return split(nextLine()); }
			public long [] nextLongs() {
				String [] L = nextStrings();
				long [] res = new long [L.length];
				for (int i = 0; i < L.length; ++i)
					res[i] = Long.parseLong(L[i]);
				return res;
			}
			public long [][] nextLongs (int N) {
				long [][] res = new long [N][];
				for (int i = 0; i < N; ++i)
					res[i] = nextLongs();
				return res;
			}
			//////////////////////////////////////////////
			private boolean eol() { return index == line.length; }
			private String readLine() {
				try {
					return r.readLine();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private final java.io.BufferedReader r;
			private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
			private MyScanner (java.io.BufferedReader r) {
				try {
					this.r = r;
					while (!r.ready())
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine() {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim(String delim, Object o, Object ... A) {
			StringBuilder b = new StringBuilder();
			append(b, o, delim);
			for (Object p : A)
				append(b, p, delim);
			return b.substring(delim.length());
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static void start() { if (t == 0) t = millis(); }
		private static void append(StringBuilder b, Object o, String delim) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					append(b, java.lang.reflect.Array.get(o, i), delim);
			} else if (o instanceof Iterable<?>)
				for (Object p : (Iterable<?>) o)
					append(b, p, delim);
			else {
				if (o instanceof Double)
					o = new java.text.DecimalFormat("#.############").format(o);
				b.append(delim).append(o);
			}
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
		private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
		private static void exit() {
			IOUtils.pw.close();
			System.out.flush();
			err("------------------");
			err(IOUtils.time());
			System.exit(0);
		}
		private static long t;
		private static long millis() { return System.currentTimeMillis(); }
		private static String time() { return "Time: " + (millis() - t) / 1000.0; }
	}
	public static void main (String[] args) { new B(); IOUtils.exit(); }
}


import static java.lang.Math.min;
import static java.util.Collections.*;

import java.util.*;

public class B {

	public B () {
		int N = sc.nextInt();
		S = sc.nextLong();
		long [][] Z = sc.nextLongs(N);

		long res = 0;
		for (int i : rep(N)) {
			long m = min(Z[i][1], Z[i][2]);
			res += Z[i][0] * m;
			Z[i][1] -= m; Z[i][2] -= m;
		}

		long T = 0;
		for (int i : rep(N))
			T += Z[i][0];
		X = ceil(T, S);

		LA = new ArrayList<>(); LB = new ArrayList<>();
		for (int i : rep(N)) {
			long D = Z[i][1] - Z[i][2];
			if (D > 0) LA.add(new long [] { Z[i][0], D });
			if (D < 0) LB.add(new long [] { Z[i][0], -D });
		}
		sort(LA, reverseOrder(by(1)));
		sort(LB, reverseOrder(by(1)));

		long p = -1, q = X, m;
		while (q - p > 1) {
			m = (p+q)/2;
			if (eval(m+1) > eval(m))
				p = m;
			else
				q = m;
		}

		res += eval(q);
		exit(res);
	}

	List<long[]> LA, LB;
	long S, X;

	long eval(long m) {
		long res = 0;

		long A = m*S;
		for (long [] a : LA) {
			long d = min(A, a[0]);
			res += d * a[1];
			A -= d;
		}

		long B = (X-m)*S;
		for (long [] b : LB) {
			long d = min(B, b[0]);
			res += d * b[1];
			B -= d;
		}

		return res;
	}

	private static Comparator<long[]> by(final int ... J) { return new Comparator<long[]>() { public int compare(long[] x, long[] y) { for (int i : J) if (x[i] != y[i]) return Long.signum(x[i] - y[i]); return 0; }}; }
	private static long ceil (long p, long q) { return fc(p, q, true); }
	private static long fc(long p, long q, boolean up) {
		if (up) {
			if (q < 0) return fc(-p, -q, true);
			else if (p < 0) return -fc(-p, q, false);
			else return (p + q - 1) / q;
		} else if (q < 0) return fc(-p, -q, false);
		else if (p < 0) return -fc(-p, q, true);
		else return p / q;
	}
	private static int [] rep(int N) { return rep(0, N); }
	private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
	////////////////////////////////////////////////////////////////////////////////////
	private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
	private static class IOUtils {
		public static class MyScanner {
			public String next() { newLine(); return line[index++]; }
			public int nextInt() { return Integer.parseInt(next()); }
			public long nextLong() { return Long.parseLong(next()); }
			public String nextLine() { line = null; return readLine(); }
			public String [] nextStrings() { return split(nextLine()); }
			public long [] nextLongs() {
				String [] L = nextStrings();
				long [] res = new long [L.length];
				for (int i = 0; i < L.length; ++i)
					res[i] = Long.parseLong(L[i]);
				return res;
			}
			public long [][] nextLongs (int N) {
				long [][] res = new long [N][];
				for (int i = 0; i < N; ++i)
					res[i] = nextLongs();
				return res;
			}
			//////////////////////////////////////////////
			private boolean eol() { return index == line.length; }
			private String readLine() {
				try {
					return r.readLine();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private final java.io.BufferedReader r;
			private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
			private MyScanner (java.io.BufferedReader r) {
				try {
					this.r = r;
					while (!r.ready())
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine() {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim(String delim, Object o, Object ... A) {
			StringBuilder b = new StringBuilder();
			append(b, o, delim);
			for (Object p : A)
				append(b, p, delim);
			return b.substring(delim.length());
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static void start() { if (t == 0) t = millis(); }
		private static void append(StringBuilder b, Object o, String delim) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					append(b, java.lang.reflect.Array.get(o, i), delim);
			} else if (o instanceof Iterable<?>)
				for (Object p : (Iterable<?>) o)
					append(b, p, delim);
			else {
				if (o instanceof Double)
					o = new java.text.DecimalFormat("#.############").format(o);
				b.append(delim).append(o);
			}
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
		private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
		private static void exit() {
			IOUtils.pw.close();
			System.out.flush();
			err("------------------");
			err(IOUtils.time());
			System.exit(0);
		}
		private static long t;
		private static long millis() { return System.currentTimeMillis(); }
		private static String time() { return "Time: " + (millis() - t) / 1000.0; }
	}
	public static void main (String[] args) { new B(); IOUtils.exit(); }
}


import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Collections.*;

import java.util.*;

public class B {

	public B () {
		int N = sc.nextInt();
		long S = sc.nextLong();
		long [][] Z = sc.nextLongs(N);

		long res = 0;
		for (int i : rep(N)) {
			if (Z[i][0] >= S) {
				res += (Z[i][0] / S) * S * max(Z[i][1], Z[i][2]);
				Z[i][0] %= S;
			}
			long m = min(Z[i][1], Z[i][2]);
			res += Z[i][0] * m;
			Z[i][1] -= m; Z[i][2] -= m;
		}

		long T = 0;
		for (int i : rep(N))
			T += Z[i][0];
		long P = ceil(T, S);

		List<long[]> LA = new ArrayList<>(), LB = new ArrayList<>();
		for (int i : rep(N)) {
			long D = Z[i][1] - Z[i][2];
			if (D > 0) LA.add(new long [] { Z[i][0], D });
			if (D < 0) LB.add(new long [] { Z[i][0], -D });
		}
		sort(LA, reverseOrder(by(1)));
		sort(LB, reverseOrder(by(1)));

		Queue<long []> QA = new LinkedList<>(), QB = new LinkedList<>();
		QA.addAll(LA); QB.addAll(LB);

		long [] RA = new long [(int)P+1], RB = new long [(int)P+1];
		for (int n : req(1, (int)P)) {
			{
				long A = S; RA[n] = RA[n-1];
				while (A > 0 && !QA.isEmpty()) {
					long [] a = QA.peek();
					if (a[0] <= A) {
						RA[n] += a[0] * a[1];
						QA.poll(); A -= a[0];
					}
					else {
						RA[n] += A * a[1];
						a[0] -= A; A = 0;
					}
				}
			}

			{
				long B = S; RB[n] = RB[n-1];
				while (B > 0 && !QB.isEmpty()) {
					long [] b = QB.peek();
					if (b[0] <= B) {
						RB[n] += b[0] * b[1];
						QB.poll(); B -= b[0];
					}
					else {
						RB[n] += B * b[1];
						b[0] -= B; B = 0;
					}
				}
			}
		}

		long R = 0;
		for (int n : req(0, (int)P))
			R = max(R, RA[n] + RB[(int)P-n]);
		res += R;

		exit(res);
	}

	private static Comparator<long[]> by(final int ... J) { return new Comparator<long[]>() { public int compare(long[] x, long[] y) { for (int i : J) if (x[i] != y[i]) return Long.signum(x[i] - y[i]); return 0; }}; }
	private static long ceil (long p, long q) { return fc(p, q, true); }
	private static long fc(long p, long q, boolean up) {
		if (up) {
			if (q < 0) return fc(-p, -q, true);
			else if (p < 0) return -fc(-p, q, false);
			else return (p + q - 1) / q;
		} else if (q < 0) return fc(-p, -q, false);
		else if (p < 0) return -fc(-p, q, true);
		else return p / q;
	}
	private static int [] rep(int N) { return rep(0, N); }
	private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
	private static int [] req(int S, int T) { return rep(S, T+1); }
	////////////////////////////////////////////////////////////////////////////////////
	private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
	private static class IOUtils {
		public static class MyScanner {
			public String next() { newLine(); return line[index++]; }
			public int nextInt() { return Integer.parseInt(next()); }
			public long nextLong() { return Long.parseLong(next()); }
			public String nextLine() { line = null; return readLine(); }
			public String [] nextStrings() { return split(nextLine()); }
			public long [] nextLongs() {
				String [] L = nextStrings();
				long [] res = new long [L.length];
				for (int i = 0; i < L.length; ++i)
					res[i] = Long.parseLong(L[i]);
				return res;
			}
			public long [][] nextLongs (int N) {
				long [][] res = new long [N][];
				for (int i = 0; i < N; ++i)
					res[i] = nextLongs();
				return res;
			}
			//////////////////////////////////////////////
			private boolean eol() { return index == line.length; }
			private String readLine() {
				try {
					return r.readLine();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private final java.io.BufferedReader r;
			private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
			private MyScanner (java.io.BufferedReader r) {
				try {
					this.r = r;
					while (!r.ready())
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine() {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim(String delim, Object o, Object ... A) {
			StringBuilder b = new StringBuilder();
			append(b, o, delim);
			for (Object p : A)
				append(b, p, delim);
			return b.substring(delim.length());
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static void start() { if (t == 0) t = millis(); }
		private static void append(StringBuilder b, Object o, String delim) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					append(b, java.lang.reflect.Array.get(o, i), delim);
			} else if (o instanceof Iterable<?>)
				for (Object p : (Iterable<?>) o)
					append(b, p, delim);
			else {
				if (o instanceof Double)
					o = new java.text.DecimalFormat("#.############").format(o);
				b.append(delim).append(o);
			}
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
		private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
		private static void exit() {
			IOUtils.pw.close();
			System.out.flush();
			err("------------------");
			err(IOUtils.time());
			System.exit(0);
		}
		private static long t;
		private static long millis() { return System.currentTimeMillis(); }
		private static String time() { return "Time: " + (millis() - t) / 1000.0; }
	}
	public static void main (String[] args) { new B(); IOUtils.exit(); }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            BOrderingPizza solver = new BOrderingPizza();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class BOrderingPizza {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int s = in.readInt();
            Person[] people = new Person[n];
            for (int i = 0; i < n; i++) {
                people[i] = new Person();
                people[i].s = in.readInt();
                people[i].a = in.readInt();
                people[i].b = in.readInt();
            }
            Arrays.sort(people, (a, b) -> -Integer.compare(a.a - a.b, b.a - b.b));

            long sum = 0;
            int prefA = 0;
            for (Person p : people) {
                sum += p.s;
                if (p.a >= p.b) {
                    prefA++;
                }
            }

            long req = DigitUtils.ceilDiv(sum, s);
            long t1 = DigitUtils.floorDiv(prefA, s);
            long t2 = DigitUtils.ceilDiv(prefA, s);

            long ans = profit(people, t1 * s, (req - t1) * s);
            long ans1 = profit(people, t2 * s, (req - t2) * s);

            out.println(Math.max(ans, ans1));
        }

        public long profit(Person[] people, long a, long b) {
            long ans = 0;
            for (Person p : people) {
                long forA = Math.min(a, p.s);
                long forB = p.s - forA;
                a -= forA;
                b -= forB;
                ans += forA * p.a + forB * p.b;
            }
            return ans;
        }

    }

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

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static long floorDiv(long a, long b) {
            return a < 0 ? -ceilDiv(-a, b) : a / b;
        }

        public static int floorDiv(int a, int b) {
            return a < 0 ? -ceilDiv(-a, b) : a / b;
        }

        public static long ceilDiv(long a, long b) {
            if (a < 0) {
                return -floorDiv(-a, b);
            }
            long c = a / b;
            if (c * b < a) {
                return c + 1;
            }
            return c;
        }

        public static int ceilDiv(int a, int b) {
            if (a < 0) {
                return -floorDiv(-a, b);
            }
            int c = a / b;
            if (c * b < a) {
                return c + 1;
            }
            return c;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(long c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(long c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            BOrderingPizza solver = new BOrderingPizza();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class BOrderingPizza {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int s = in.readInt();
            Person[] people = new Person[n];
            for (int i = 0; i < n; i++) {
                people[i] = new Person();
                people[i].s = in.readInt();
                people[i].a = in.readInt();
                people[i].b = in.readInt();
            }
            Arrays.sort(people, (a, b) -> -Integer.compare(a.a - a.b, b.a - b.b));

            long sum = 0;
            long prefA = 0;
            for (Person p : people) {
                sum += p.s;
                if (p.a >= p.b) {
                    prefA += p.s;
                }
            }

            long req = DigitUtils.ceilDiv(sum, s);
            long t1 = DigitUtils.floorDiv(prefA, s);
            long t2 = DigitUtils.ceilDiv(prefA, s);

            long ans = profit(people, t1 * s, (req - t1) * s);
            long ans1 = profit(people, t2 * s, (req - t2) * s);

            out.println(Math.max(ans, ans1));
        }

        public long profit(Person[] people, long a, long b) {
            long ans = 0;
            for (Person p : people) {
                long forA = Math.min(a, p.s);
                long forB = p.s - forA;
                a -= forA;
                b -= forB;
                ans += forA * p.a + forB * p.b;
            }
            return ans;
        }

    }

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

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static long floorDiv(long a, long b) {
            return a < 0 ? -ceilDiv(-a, b) : a / b;
        }

        public static long ceilDiv(long a, long b) {
            if (a < 0) {
                return -floorDiv(-a, b);
            }
            long c = a / b;
            if (c * b < a) {
                return c + 1;
            }
            return c;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(long c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(long c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            BOrderingPizza solver = new BOrderingPizza();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class BOrderingPizza {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int s = in.readInt();
            Person[] people = new Person[n];
            for (int i = 0; i < n; i++) {
                people[i] = new Person();
                people[i].s = in.readInt();
                people[i].a = in.readInt();
                people[i].b = in.readInt();
            }
            Arrays.sort(people, (a, b) -> -Integer.compare(a.a - a.b, b.a - b.b));

            long sum = 0;
            long prefA = 0;
            for (Person p : people) {
                sum += p.s;
                if (p.a >= p.b) {
                    prefA += p.s;
                }
            }

            long req = DigitUtils.ceilDiv(sum, s);
            long t1 = DigitUtils.floorDiv(prefA, s);

            long ans = 0;
            for (long i = t1 - 2; i <= t1 + 2; i++) {
                if (i < 0 || i > req) {
                    continue;
                }
                ans = Math.max(ans, profit(people, i * s, (req - i) * s));
            }

            out.println(ans);
        }

        public long profit(Person[] people, long a, long b) {
            long ans = 0;
            for (Person p : people) {
                long forA = Math.min(a, p.s);
                long forB = p.s - forA;
                a -= forA;
                b -= forB;
                ans += forA * p.a + forB * p.b;
            }
            return ans;
        }

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static long floorDiv(long a, long b) {
            return a < 0 ? -ceilDiv(-a, b) : a / b;
        }

        public static long ceilDiv(long a, long b) {
            if (a < 0) {
                return -floorDiv(-a, b);
            }
            long c = a / b;
            if (c * b < a) {
                return c + 1;
            }
            return c;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

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

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(long c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(long c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            FastOutput out = new FastOutput(outputStream);
            BOrderingPizza solver = new BOrderingPizza();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class BOrderingPizza {
        public void solve(int testNumber, FastInput in, FastOutput out) {
            int n = in.readInt();
            int s = in.readInt();
            Person[] people = new Person[n];
            for (int i = 0; i < n; i++) {
                people[i] = new Person();
                people[i].s = in.readInt();
                people[i].a = in.readInt();
                people[i].b = in.readInt();
            }
            Arrays.sort(people, (a, b) -> -Integer.compare(a.a - a.b, b.a - b.b));

            long sum = 0;
            long prefA = 0;
            for (Person p : people) {
                sum += p.s;
                if (p.a >= p.b) {
                    prefA += p.s;
                }
            }

            long req = DigitUtils.ceilDiv(sum, s);
            long t1 = DigitUtils.floorDiv(prefA, s);

            long ans = 0;
            for (long i = t1 - 1; i <= t1 + 1; i++) {
                if (i < 0 || i > req) {
                    continue;
                }
                ans = Math.max(ans, profit(people, i * s, (req - i) * s));
            }

            out.println(ans);
        }

        public long profit(Person[] people, long a, long b) {
            long ans = 0;
            int l = 0;
            int r = people.length - 1;
            while (l <= r && people[l].a > people[l].b && a > 0) {
                long forA = Math.min(people[l].s, a);
                long forB = people[l].s - forA;
                a -= forA;
                b -= forB;
                ans += forA * people[l].a + forB * people[l].b;
                l++;
            }
            while (l <= r && people[r].a < people[r].b && b > 0) {
                long forB = Math.min(people[r].s, b);
                long forA = people[r].s - forB;
                a -= forA;
                b -= forB;
                ans += forA * people[r].a + forB * people[r].b;
                r--;
            }

            while (l <= r) {
                long forA = Math.min(people[l].s, a);
                long forB = people[l].s - forA;
                a -= forA;
                b -= forB;
                ans += forA * people[l].a + forB * people[l].b;
                l++;
            }

            return ans;
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class FastOutput implements AutoCloseable, Closeable, Appendable {
        private StringBuilder cache = new StringBuilder(10 << 20);
        private final Writer os;

        public FastOutput append(CharSequence csq) {
            cache.append(csq);
            return this;
        }

        public FastOutput append(CharSequence csq, int start, int end) {
            cache.append(csq, start, end);
            return this;
        }

        public FastOutput(Writer os) {
            this.os = os;
        }

        public FastOutput(OutputStream os) {
            this(new OutputStreamWriter(os));
        }

        public FastOutput append(char c) {
            cache.append(c);
            return this;
        }

        public FastOutput append(long c) {
            cache.append(c);
            return this;
        }

        public FastOutput println(long c) {
            return append(c).println();
        }

        public FastOutput println() {
            cache.append(System.lineSeparator());
            return this;
        }

        public FastOutput flush() {
            try {
                os.append(cache);
                os.flush();
                cache.setLength(0);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            return this;
        }

        public void close() {
            flush();
            try {
                os.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        public String toString() {
            return cache.toString();
        }

    }

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

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static long floorDiv(long a, long b) {
            return a < 0 ? -ceilDiv(-a, b) : a / b;
        }

        public static long ceilDiv(long a, long b) {
            if (a < 0) {
                return -floorDiv(-a, b);
            }
            long c = a / b;
            if (c * b < a) {
                return c + 1;
            }
            return c;
        }

    }
}


import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

public class Test {
    final int N = 123456;
    int n, s;
    long total = 0, ps = 0;
    int[][] h1 = new int[N][3], h2 = new int[N][3];
    Integer[] id1, id2;
    int h1i, h1j, h2i, h2j;

    int readInt() {
        int ans = 0;
        try {
            boolean start = false;
            for (int c = 0; (c = System.in.read()) != -1; ) {
                if (c >= '0' && c <= '9') {
                    start = true;
                    ans = ans * 10 + c - '0';
                } else if (start) break;
            }
        } catch (IOException e) {
        }
        return ans;
    }

    void sort(Integer[] id, int[][] h) {
        Arrays.sort(id, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return (h[a][0] - h[a][1]) - (h[b][0] - h[b][1]);
            }
        });
    }

    void start() {
        n = readInt();
        s = readInt();
        int c1 = 0, c2 = 0;
        for (int i = 0; i < n; i++) {
            int c = readInt(), a = readInt(), b = readInt();
            if (a > b) {
                h1[c1][0] = a;
                h1[c1][1] = b;
                h1[c1][2] = c;
                c1++;
            } else {
                h2[c2][0] = b;
                h2[c2][1] = a;
                h2[c2][2] = c;
                c2++;
            }
        }
        id1 = new Integer[c1];
        id2 = new Integer[c2];
        for (int i = 0; i < c1; i++) id1[i] = i;
        for (int i = 0; i < c2; i++) id2[i] = i;
        sort(id1, h1);
        sort(id2, h2);

        long t1a = 0, t1b = 0, t2a = 0, t2b = 0, cnt1 = 0, cnt2 = 0;
        for (int i = c1 - 1; i >= 0; i--) {
            int j = id1[i];
            total += h1[j][0]*h1[j][2];
            cnt1 += h1[j][2];
        }
        long m = cnt1 % s;
        cnt1 = m;
        if (m > 0) {
            for (int i = 0; i < c1 && m > 0; i++) {
                int j = id1[i];
                long c = Math.min(m, h1[j][2]);
                t1a += c*h1[j][0];
                t1b += c*h1[j][1];
                m -= c;
            }
            total -= t1a;
        }
        for (int i = c2 - 1; i >= 0; i--) {
            int j = id2[i];
            total += h2[j][0]*h2[j][2];
            cnt2 += h2[j][2];
        }
        m = cnt2 % s;
        cnt2 = m;
        if (m > 0) {
            for (int i = 0; i < c2 && m > 0; i++) {
                int j = id2[i];
                long c = Math.min(m, h2[j][2]);
                t2a += c*h2[j][0];
                t2b += c*h2[j][1];
                m -= c;
            }
            total -= t2a;
        }
        if (cnt1 + cnt2 > 0 && cnt1 + cnt2 <= s) {
            if (t1a + t2b > t2a + t1b) total += t1a + t2b;
            else total += t2a + t1b;
        }

        System.out.println(total);
    }

    public static void main(String[] args) {
        new Test().start();
    }
}


import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

public class Test {
    final int N = 123456;
    int n, s;
    long total = 0;
    int[][] h1 = new int[N][3], h2 = new int[N][3];

    int readInt() {
        int ans = 0;
        try {
            boolean start = false;
            for (int c = 0; (c = System.in.read()) != -1; ) {
                if (c >= '0' && c <= '9') {
                    start = true;
                    ans = ans * 10 + c - '0';
                } else if (start) break;
            }
        } catch (IOException e) {
        }
        return ans;
    }

    void start() {
        n = readInt();
        s = readInt();
        int c1 = 0, c2 = 0;
        for (int i = 0; i < n; i++) {
            int c = readInt(), a = readInt(), b = readInt();
            if (a > b) {
                h1[c1][0] = a; h1[c1][1] = b; h1[c1][2] = c;
                c1++;
            } else {
                h2[c2][0] = b; h2[c2][1] = a; h2[c2][2] = c;
                c2++;
            }
        }
        Integer[] id1 = new Integer[c1], id2 = new Integer[c2];
        for (int i = 0; i < c1; i++) id1[i] = i;
        for (int i = 0; i < c2; i++) id2[i] = i;
        Arrays.sort(id1, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return (h1[a][0] - h1[a][1]) - (h1[b][0] - h1[b][1]);
            }
        });
        Arrays.sort(id2, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return (h2[a][0] - h2[a][1]) - (h2[b][0] - h2[b][1]);
            }
        });
        int h1i = 0, h1j = c1 - 1, h2i = 0, h2j = c2 - 1;
        while (true) {
            long hp1 = 0, hp2 = 0, cnt1 = 0, cnt2 = 0;
            int i = 0;
            for (i = h1j; i >= h1i && cnt1 < s; i--) {
                int j = id1[i];
                long c = Math.min(h1[j][2], s - cnt1);
                hp1 += (h1[j][0] - h1[j][1])*c;
                cnt1 += c;
            }
            for (i = h2j; i >= h2i && cnt2 < s; i--) {
                int j = id2[i];
                long c = Math.min(h2[j][2], s - cnt2);
                hp2 += (h2[j][0] - h2[j][1])*c;
                cnt2 += c;
            }
            if (hp1 > hp2) {
                long cnt = cnt1;
                while (cnt > 0) {
                    int j = id1[h1j];
                    long c = Math.min(cnt, h1[j][2]);
                    h1[j][2] -= c;
                    cnt -= c;
                    total += c*h1[j][0];
                    if (h1[j][2] == 0) h1j--;
                }
                if (cnt1 < s) {
                    cnt = s - cnt1;
                    while (cnt > 0 && h2i <= h2j) {
                        int j = id2[h2i];
                        long c = Math.min(cnt, h2[j][2]);
                        h2[j][2] -= c;
                        cnt -= c;
                        total += h2[j][1]*c;
                        if (h2[j][2] == 0) h2i++;
                    }
                }
            } else {
                long cnt = cnt2;
                while (cnt > 0) {
                    int j = id2[h2j];
                    long c = Math.min(cnt, h2[j][2]);
                    h2[j][2] -= c;
                    cnt -= c;
                    total += c*h2[j][0];
                    if (h2[j][2] == 0) h2j--;
                }
                if (cnt2 < s) {
                    cnt = s - cnt2;
                    while (cnt > 0 && h1i <= h1j) {
                        int j = id1[h1i];
                        long c = Math.min(cnt, h1[j][2]);
                        h1[j][2] -= c;
                        cnt -= c;
                        total += h1[j][1]*c;
                        if (h1[j][2] == 0) h1i++;
                    }
                }
            }
            if (h1i > h1j && h2i > h2j) break;
        }
        System.out.println(total);
    }

    public static void main(String[] args) {
        new Test().start();
    }
}


import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

public class Test {
    final int N = 123456;
    int n, s;
    long total = 0;
    int[][] h1 = new int[N][3], h2 = new int[N][3];
    Integer[] id1, id2;
    int h1i, h1j, h2i, h2j;

    int readInt() {
        int ans = 0;
        try {
            boolean start = false;
            for (int c = 0; (c = System.in.read()) != -1; ) {
                if (c >= '0' && c <= '9') {
                    start = true;
                    ans = ans * 10 + c - '0';
                } else if (start) break;
            }
        } catch (IOException e) {
        }
        return ans;
    }

    void sort(Integer[] id, int[][] h) {
        Arrays.sort(id, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return (h[a][0] - h[a][1]) - (h[b][0] - h[b][1]);
            }
        });
    }

    int whole(Integer[] id, int[][] h, int start, int end) {
        long cnt = 0;
        for (int i = end; i >= start; i--) {
            int j = id[i];
            cnt += h[j][2];
        }
        if (cnt >= 2 * s) cnt = (cnt / s) * s - s;
        else cnt = 0;
        while (cnt > 0) {
            int j = id[end];
            long c = Math.min(h[j][2], cnt);
            h[j][2] -= c;
            cnt -= c;
            total += c * h[j][0];
            if (h[j][2] == 0) end--;
        }
        return end;
    }

    int[] take(Integer[] id1, Integer[] id2, int[][] h1, int[][] h2, int h1i, int h1j, int h2i, int h2j, long cnt1) {
        long cnt = cnt1;
        while (cnt > 0) {
            int j = id1[h1j];
            long c = Math.min(cnt, h1[j][2]);
            h1[j][2] -= c;
            cnt -= c;
            total += c * h1[j][0];
            if (h1[j][2] == 0) h1j--;
        }
        if (cnt1 < s) {
            cnt = s - cnt1;
            while (cnt > 0 && h2i <= h2j) {
                int j = id2[h2i];
                long c = Math.min(cnt, h2[j][2]);
                h2[j][2] -= c;
                cnt -= c;
                total += h2[j][1] * c;
                if (h2[j][2] == 0) h2i++;
            }
        }
        return new int[]{h1j, h2i};
    }

    void start() {
        n = readInt();
        s = readInt();
        int c1 = 0, c2 = 0;
        for (int i = 0; i < n; i++) {
            int c = readInt(), a = readInt(), b = readInt();
            if (a > b) {
                h1[c1][0] = a;
                h1[c1][1] = b;
                h1[c1][2] = c;
                c1++;
            } else {
                h2[c2][0] = b;
                h2[c2][1] = a;
                h2[c2][2] = c;
                c2++;
            }
        }
        id1 = new Integer[c1];
        id2 = new Integer[c2];
        for (int i = 0; i < c1; i++) id1[i] = i;
        for (int i = 0; i < c2; i++) id2[i] = i;
        sort(id1, h1);
        sort(id2, h2);
        h1i = 0;
        h1j = c1 - 1;
        h2i = 0;
        h2j = c2 - 1;
        h1j = whole(id1, h1, h1i, h1j);
        h2j = whole(id2, h2, h2i, h2j);

        while (true) {
            long hp1 = 0, hp2 = 0, cnt1 = 0, cnt2 = 0;
            int i = 0;
            for (i = h1j; i >= h1i && cnt1 < s; i--) {
                int j = id1[i];
                long c = Math.min(h1[j][2], s - cnt1);
                hp1 += (h1[j][0] - h1[j][1]) * c;
                cnt1 += c;
            }
            for (i = h2j; i >= h2i && cnt2 < s; i--) {
                int j = id2[i];
                long c = Math.min(h2[j][2], s - cnt2);
                hp2 += (h2[j][0] - h2[j][1]) * c;
                cnt2 += c;
            }
            if (hp1 > hp2) {
                int[] r = take(id1, id2, h1, h2, h1i, h1j, h2i, h2j, cnt1);
                h1j = r[0];
                h2i = r[1];
            } else {
                int[] r = take(id2, id1, h2, h1, h2i, h2j, h1i, h1j, cnt2);
                h2j = r[1];
                h1i = r[1];
            }
            if (h1i > h1j && h2i > h2j) break;
        }
        System.out.println(total);
    }

    public static void main(String[] args) {
        new Test().start();
    }
}