It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.

It is known that the i-th contestant will eat s_{i} slices of pizza, and gain a_{i} happiness for each slice of type 1 pizza they eat, and b_{i} happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?


-----Input-----

The first line of input will contain integers N and S (1 ≤ N ≤ 10^5, 1 ≤ S ≤ 10^5), the number of contestants and the number of slices per pizza, respectively. N lines follow.

The i-th such line contains integers s_{i}, a_{i}, and b_{i} (1 ≤ s_{i} ≤ 10^5, 1 ≤ a_{i} ≤ 10^5, 1 ≤ b_{i} ≤ 10^5), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.


-----Output-----

Print the maximum total happiness that can be achieved.


-----Examples-----
Input
3 12
3 5 7
4 6 7
5 9 5

Output
84

Input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6

Output
314



-----Note-----

In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.

Difficulty: HARD

Solutions:
from collections import namedtuple
Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy'])

def happy_diff(m):
	return m.a_happy - m.b_happy

def main():
	(input_strings_members, parts) = read_input()
	(a_members, b_members, other_members) = prepare_members(input_strings_members)
	print(count_parts(a_members, b_members, other_members, parts))

def read_input():
	counts_str = input().split()
	(members_count, parts) = map(int, counts_str)
	return ([input() for _ in range(members_count)], parts)

def prepare_members(input_strings_members):
	a_members = []
	b_members = []
	other_members = []
	for line in input_strings_members:
		m = Member(*map(int, line.split()))
		if happy_diff(m) > 0:
			a_members.append(m)
		elif happy_diff(m) < 0:
			b_members.append(m)
		else:
			other_members.append(m)
	return (a_members, b_members, other_members)

def count_parts(a_members, b_members, other_members, parts_in_one):
	a_members.sort(key=lambda m: happy_diff(m), reverse=False)
	a_modulo = sum((m.parts for m in a_members)) % parts_in_one
	(a_modulo_members, a_happy_members) = split_members_into_happy_groups(a_members, a_modulo)
	a_happy = sum((m.a_happy * m.parts for m in a_happy_members))
	b_members.sort(key=lambda m: happy_diff(m), reverse=True)
	b_modulo = sum((m.parts for m in b_members)) % parts_in_one
	(b_modulo_members, b_happy_members) = split_members_into_happy_groups(b_members, b_modulo)
	b_happy = sum((m.b_happy * m.parts for m in b_happy_members))
	last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one)
	return a_happy + b_happy + last_happy

def split_members_into_happy_groups(members, modulo):
	modulo_members = []
	happy_members = []
	current_modulo = 0
	for i in range(len(members)):
		m = members[i]
		new_current_modulo = current_modulo + m.parts
		if new_current_modulo < modulo:
			modulo_members.append(m)
			current_modulo = new_current_modulo
			continue
		modulo_members.append(Member(modulo - current_modulo, m.a_happy, m.b_happy))
		if new_current_modulo > modulo:
			happy_members.append(Member(new_current_modulo - modulo, m.a_happy, m.b_happy))
		if i + 1 < len(members):
			happy_members.extend(members[i + 1:])
		break
	return (modulo_members, happy_members)

def count_last_pizzas_happy(a, b, other, parts_in_one):
	last_sorted_members = a + other + b
	if sum((m.parts for m in last_sorted_members)) <= parts_in_one:
		return max(sum((m.a_happy * m.parts for m in last_sorted_members)), sum((m.b_happy * m.parts for m in last_sorted_members)))
	return sum((m.a_happy * m.parts for m in a + other)) + sum((m.b_happy * m.parts for m in b))

def test1():
	(a, b, c) = prepare_members(['7 4 7', '5 8 8', '12 5 8', '6 11 6', '3 3 7', '5 9 6'])
	assert count_parts(a, b, c, 10) == 314

def test2():
	(a, b, c) = prepare_members(['3 5 7', '4 6 7', '5 9 5'])
	assert count_parts(a, b, c, 12) == 84

def test3():
	(a, b, c) = prepare_members(['2 3 1', '2 2 2', '2 1 3'])
	assert count_parts(a, b, c, 3) == 16

def test4():
	(a, b, c) = prepare_members(['2 1 4', '2 3 1'])
	assert count_parts(a, b, c, 3) == 14

def test5():
	(a, b, c) = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1'])
	assert count_parts(a, b, c, 3) == (8 + 6 + 4) * 2

def test6():
	(a, b, c) = prepare_members(['2 1 2', '2 2 1', '2 1 3', '2 3 1', '2 1 4', '2 4 1'])
	assert count_parts(a, b, c, 5) == 16 + 16 + 3

def test_without_last_pizzas():
	(a, b, c) = prepare_members(['3 3 1', '3 5 6'])
	assert count_parts(a, b, c, 3) == 27

def test_with_one_last_pizza():
	(a, b, c) = prepare_members(['2 3 1', '1 5 6'])
	assert count_parts(a, b, c, 3) == 11

def test_with_two_last_pizzas():
	(a, b, c) = prepare_members(['2 3 4', '2 3 1', '1 1 1'])
	assert count_parts(a, b, c, 3) == 15

def test_without_different_happies():
	(a, b, c) = prepare_members(['2 2 2', '4 1 1', '5 6 6'])
	assert count_parts(a, b, c, 3) == 38
main()


def solve(arr):
	arr.sort(key=lambda q: q[1] - q[0])
	m = sum((si for (a, b, si) in arr))
	k = s * (m // s)
	n = m - k
	(x, y, z) = (0, 0, 0)
	for (a, b, si) in arr:
		if k >= si:
			k -= si
			z += si * a
		elif k > 0:
			z += k * a
			x = (si - k) * a
			y = (si - k) * b
			k = 0
		else:
			x += si * a
			y += si * b
	return (x, y, z, n)
(n, s) = map(int, input().split())
(arr1, arr2) = ([], [])
for i in range(n):
	(si, ai, bi) = map(int, input().split())
	if ai > bi:
		arr1.append((ai, bi, si))
	else:
		arr2.append((bi, ai, si))
(x1, y1, z1, n1) = solve(arr1)
(x2, y2, z2, n2) = solve(arr2)
d = x1 + x2 if n1 + n2 > s else max(x1 + y2, x2 + y1)
print(z1 + z2 + d)


import math
import collections
import bisect
import heapq
import time
import random
(N, S) = map(int, input().split())
M = []
for i in range(N):
	M.append([int(x) for x in input().split()])
s = [M[i][0] for i in range(N)]
a = [M[i][1] for i in range(N)]
b = [M[i][2] for i in range(N)]
total = sum(s)
numpizza = int(math.ceil(total / S))
numslice = numpizza * S
sab = sorted([(a[i] - b[i], i) for i in range(N)], reverse=True)
pa = 0
pb = 0
pab = 0
maxHappiness = 0
for i in range(N):
	if a[i] > b[i]:
		pa += s[i]
	elif a[i] < b[i]:
		pb += s[i]
	else:
		pab += s[i]
sa = int(math.ceil(pa / S)) * S
sb = int(math.ceil(pb / S)) * S
pab -= sa + sb - pa - pb
pab = max(pab, 0)
if sa // S + sb // S + int(math.ceil(pab / S)) == numpizza:
	print(sum([s[i] * (a[i] if a[i] > b[i] else b[i]) for i in range(N)]))
	exit(0)
if pa == 0 and pb == 0:
	print(sum([s[i] * a[i] for i in range(N)] or [0]))
	exit(0)
if pa == 0:
	print(sum([s[i] * b[i] for i in range(N)] or [0]))
	exit(0)
if pb == 0:
	print(sum([s[i] * a[i] for i in range(N)] or [0]))
	exit(0)
sbak = s
for pza in range(pa // S, (pa + pab) // S + 2):
	pzb = numpizza - pza
	aslice = pza * S
	bslice = pzb * S
	h = 0
	s = [x for x in sbak]
	for j in range(N):
		(d, i) = sab[j]
		if d > 0:
			if aslice >= s[i]:
				h += s[i] * a[i]
				aslice -= s[i]
				s[i] = 0
			elif aslice > 0:
				h += a[i] * aslice
				s[i] -= aslice
				aslice = 0
		else:
			break
	for j in range(N - 1, -1, -1):
		(d, i) = sab[j]
		if d < 0:
			if bslice >= s[i]:
				h += s[i] * b[i]
				bslice -= s[i]
				s[i] = 0
			elif bslice > 0:
				h += bslice * b[i]
				s[i] -= bslice
				bslice = 0
		else:
			break
	if aslice == 0:
		for i in range(N):
			if s[i] != 0:
				h += s[i] * b[i]
				bslice -= s[i]
	elif bslice == 0:
		for i in range(N):
			if s[i] != 0:
				h += s[i] * a[i]
				aslice -= s[i]
	else:
		remain = [(s[i], a[i], b[i]) for i in range(N) if s[i] > 0 and a[i] != b[i]]
		for (u, v, w) in remain:
			if v > w:
				if aslice > 0:
					if aslice > u:
						h += u * v
						aslice -= u
					else:
						h += aslice * v
						h += (u - aslice) * w
						bslice -= u - aslice
						aslice = 0
				else:
					h += u * w
					bslice -= u
			elif bslice > 0:
				if bslice > u:
					h += u * w
					bslice -= u
				else:
					h += bslice * w
					h += (u - bslice) * v
					aslice -= u - bslice
					bslice = 0
			else:
				h += u * v
				aslice -= u
		h += sum([s[i] * a[i] for i in range(N) if a[i] == b[i]] or [0])
	maxHappiness = max(maxHappiness, h)
print(maxHappiness)


def get_losts(persons, count):
	persons.sort(key=lambda p: p.lost)
	losts = 0
	i = 0
	while count > 0:
		df = min(count, persons[i].s)
		losts += df * persons[i].lost
		count -= df
		i += 1
	return losts

class Person:

	def __init__(self, _s, _a, _b, _lost):
		self.s = _s
		self.a = _a
		self.b = _b
		self.lost = _lost
(n, m) = map(int, input().split())
s_count = 0
a_pizza = list()
a_count = 0
a_points = 0
b_pizza = list()
b_count = 0
b_points = 0
neutral_points = 0
neutral_count = 0
for i in range(n):
	(s, a, b) = map(int, input().split())
	s_count += s
	if a == b:
		neutral_points += s * a
		s_count -= s
		neutral_count += s
	elif a > b:
		a_pizza.append(Person(s, a, b, a - b))
		a_count += s
		a_points += s * a
	else:
		b_pizza.append(Person(s, a, b, b - a))
		b_count += s
		b_points += s * b
a_lost = a_count % m
b_lost = b_count % m
if a_lost + b_lost + neutral_count > m or a_lost == 0 or b_lost == 0:
	print(neutral_points + a_points + b_points)
else:
	a_lost = get_losts(a_pizza, a_lost)
	b_lost = get_losts(b_pizza, b_lost)
	print(neutral_points + a_points + b_points - min(a_lost, b_lost))


import math

class Person:

	def __init__(self, slices, a_happiness, b_happiness):
		self.slices = slices
		self.a_happiness = a_happiness
		self.b_happiness = b_happiness
		self.choice = None

	def make_greedy_choice(self):
		if self.a_happiness > self.b_happiness:
			self.choice = (self.slices, 0)
		else:
			self.choice = (0, self.slices)

	def happiness_for(self, a_slices, b_slices):
		return a_slices * self.a_happiness + b_slices * self.b_happiness

	@property
	def happiness(self):
		if self.choice is None:
			raise RuntimeError('need pizza choice to compute happiness')
		return self.happiness_for(self.choice[0], self.choice[1])

	def choose(self, a, b):
		self.choice = (a, b)

	def __repr__(self):
		return 'Person({}, {}, {})'.format(self.slices, self.a_happiness, self.b_happiness)
(n, slices) = [int(x) for x in input().split()]
people = []
for _ in range(n):
	people.append(Person(*[int(x) for x in input().split()]))
required_slices = sum([person.slices for person in people])
quantity = math.ceil(required_slices / slices)
for person in people:
	person.make_greedy_choice()
greedy_happiness = sum([person.happiness for person in people])
greedy_a_slices = sum([person.choice[0] for person in people])
greedy_b_slices = sum([person.choice[1] for person in people])
greedy_quantity = math.ceil(greedy_a_slices / slices) + math.ceil(greedy_b_slices / slices)
if greedy_quantity <= quantity:
	print(greedy_happiness)
else:
	slices_to_change = greedy_a_slices % slices
	a_people = filter(lambda person: person.choice[0] > 0, people)
	a_reduction = 0
	a_people = sorted(a_people, key=lambda person: person.a_happiness - person.b_happiness)
	for person in a_people:
		if slices_to_change == 0:
			break
		can_change = min(person.choice[0], slices_to_change)
		a_reduction += (person.a_happiness - person.b_happiness) * can_change
		slices_to_change -= can_change
	slices_to_change = greedy_b_slices % slices
	b_people = filter(lambda person: person.choice[1] > 0, people)
	b_reduction = 0
	b_people = sorted(b_people, key=lambda person: person.b_happiness - person.a_happiness)
	for person in b_people:
		if slices_to_change == 0:
			break
		can_change = min(person.choice[1], slices_to_change)
		b_reduction += (person.b_happiness - person.a_happiness) * can_change
		slices_to_change -= can_change
	print(greedy_happiness - min(a_reduction, b_reduction))


import sys
(n, s) = tuple(map(int, input().split()))
x = []
for i in range(n):
	(si, a, b) = tuple(map(int, input().split()))
	x.append([si, a, b])
x = sorted(x, key=lambda t: abs(t[1] - t[2]))
labels = []
sum1 = 0
sum2 = 0
res = 0
for i in range(len(x)):
	res += x[i][0] * max(x[i][1], x[i][2])
	if x[i][1] > x[i][2]:
		sum1 += x[i][0]
		labels.append(1)
	elif x[i][1] < x[i][2]:
		sum2 += x[i][0]
		labels.append(2)
	elif sum1 > sum2:
		sum2 += x[i][0]
		labels.append(2)
	else:
		sum1 = x[i][0]
		labels.append(1)
if (sum1 - 1) // s + 1 + (sum2 - 1) // s + 1 == (sum1 + sum2 - 1) // s + 1:
	print(res)
	sys.exit(0)
s1 = sum1
s2 = sum2
res1 = res
for i in range(len(labels)):
	c = False
	if labels[i] == 1:
		j = 0
		while x[i][0] - j != 0:
			if s1 % s == 0 or s2 % s == 0:
				c = True
				break
			j += 1
			s1 -= 1
			s2 += 1
			res1 -= abs(x[i][1] - x[i][2])
	if c:
		break
s1 = sum1
s2 = sum2
for i in range(len(labels)):
	c = False
	if labels[i] == 2:
		j = 0
		while x[i][0] - j != 0:
			if s1 % s == 0 or s2 % s == 0:
				c = True
				break
			j += 1
			s1 += 1
			s2 -= 1
			res -= abs(x[i][1] - x[i][2])
	if c:
		break
print(max(res1, res))


(n, s) = map(int, input().split())
data = [[] for i in range(n)]
sec = 0
fir = 0
su = 0
for i in range(n):
	a = list(map(int, input().split()))
	data[i].append(abs(a[1] - a[2]))
	if a[1] >= a[2]:
		fir += a[0]
		su += a[0] * a[1]
		data[i].append(0)
	else:
		sec += a[0]
		su += a[0] * a[2]
		data[i].append(1)
	data[i] += a
data = sorted(data)
fis = fir % s
sis = sec % s
if fis + sis > s or (fis == 0 or sis == 0):
	print(su)
else:
	cou = fis
	k = 0
	su1 = su
	while cou > 0 and k < n:
		if data[k][1] == 1:
			k += 1
			continue
		su1 -= min(cou, data[k][2]) * data[k][0]
		cou -= min(cou, data[k][2])
		k += 1
	cou = sis
	k = 0
	su2 = su
	while cou > 0 and k < n:
		if data[k][1] == 0:
			k += 1
			continue
		su2 -= min(cou, data[k][2]) * data[k][0]
		cou -= min(cou, data[k][2])
		k += 1
	print(max(su1, su2))


def bins(sortedlist, x):
	n = len(sortedlist)
	start = 0
	end = n - 1
	while start <= end:
		mid = int((start + end) / 2)
		if x == sortedlist[mid][0]:
			return mid
		elif x < sortedlist[mid][0]:
			end = mid - 1
		else:
			start = mid + 1
	if sortedlist[mid][0] <= x:
		return mid
	else:
		return mid - 1
(n, s) = map(int, input().split())
hap = []
for i in range(n):
	hap.append(list(map(int, input().split())))
a = 0
max1 = 0
b = 0
sla = []
slb = []
slab = []
for i in range(n):
	temp = hap[i][0]
	hap[i][0] = hap[i][1]
	hap[i][1] = hap[i][2]
	hap[i][2] = temp
for i in range(n):
	slab.append([hap[i][0] - hap[i][1], hap[i][2]])
happi = 0
for i in range(n):
	if hap[i][0] > hap[i][1]:
		a += hap[i][2]
		happi += hap[i][2] * hap[i][0]
	else:
		b += hap[i][2]
		happi += hap[i][2] * hap[i][1]
sla.sort()
slb.sort()
slab.sort()
if a % s + b % s > s:
	print(happi)
else:
	loc = bins(slab, 0)
	happia = happi
	count = 0
	b = b % s
	a = a % s
	left = b % s
	while left > 0:
		if slab[loc + count][1] < left:
			happia += slab[loc + count][0] * slab[loc + count][1]
			left -= slab[loc + count][1]
		else:
			happia += slab[loc + count][0] * left
			break
		count -= 1
	left = a % s
	count = 0
	happib = happi
	while loc < n and slab[loc][0] <= 0:
		loc += 1
	while left > 0:
		if slab[loc + count][1] < left:
			happib -= slab[loc + count][0] * slab[loc + count][1]
			left -= slab[loc + count][1]
		else:
			happib -= slab[loc + count][0] * left
			break
		count += 1
	print(max(happia, happib))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=300006, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.height = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val == 0:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
			elif val >= 1:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left

	def do(self, temp):
		if not temp:
			return 0
		ter = temp
		temp.height = self.do(ter.left) + self.do(ter.right)
		if temp.height == 0:
			temp.height += 1
		return temp.height

	def query(self, xor):
		self.temp = self.root
		cur = 0
		i = 31
		while i > -1:
			val = xor & 1 << i
			if not self.temp:
				return cur
			if val >= 1:
				self.opp = self.temp.right
				if self.temp.left:
					self.temp = self.temp.left
				else:
					return cur
			else:
				self.opp = self.temp.left
				if self.temp.right:
					self.temp = self.temp.right
				else:
					return cur
			if self.temp.height == pow(2, i):
				cur += 1 << i
				self.temp = self.opp
			i -= 1
		return cur
(n, s) = map(int, input().split())
w = []
w1 = []
sw = 0
sw1 = 0
ans = 0
qw = 0
qw1 = 0
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b < c:
		w.append((c - b, a))
		sw += a
		qw += a * (c - b)
	else:
		w1.append((b - c, a))
		sw1 += a
		qw1 += a * (b - c)
	ans += a * max(c, b)
w.sort()
w1.sort()
tr = sw // s * s
tr1 = sw1 // s * s
for i in range(len(w) - 1, -1, -1):
	(b, a) = w[i]
	if tr >= a:
		sw -= a
		qw -= a * b
		tr -= a
	else:
		sw -= tr
		qw -= tr * b
		tr = 0
		break
for i in range(len(w1) - 1, -1, -1):
	(b, a) = w1[i]
	if tr1 >= a:
		sw1 -= a
		qw1 -= a * b
		tr1 -= a
	else:
		sw1 -= tr1
		qw1 -= tr1 * b
		tr1 = 0
		break
if sw + sw1 > s:
	print(ans)
else:
	print(ans - min(qw, qw1))


from sys import stdin
from collections import deque
(n, S) = [int(x) for x in stdin.readline().split()]
ppl = []
base = 0
tSlices = 0
for dude in range(n):
	(s, a, b) = [int(x) for x in stdin.readline().split()]
	base += s * a
	tSlices += s
	ppl.append([b - a, s])
if tSlices % S != 0:
	ppl.append([0, S - tSlices % S])
ppl.sort(reverse=True)
totalS = 0
totalH = 0
for (h, s) in ppl:
	if totalS + s < S:
		totalS += s
		totalH += h * s
	else:
		s -= S - totalS
		totalH += h * (S - totalS)
		if totalH > 0:
			base += totalH
		else:
			break
		totalS = 0
		totalH = 0
		if h > 0:
			base += h * (s // S * S)
			totalS = s % S
			totalH = h * (s % S)
		else:
			break
print(base)


(n, S) = (0, 0)
s = []
a = []
b = []

class node:

	def __init__(self, x, id):
		self.x = x
		self.id = id
		return

	def __lt__(self, p):
		return self.x < p.x
c = []
(i, f) = (0, 0)
(ans, sum, a1, a2) = (0, 0, 0, 0)
(s1, s2) = (0, 0)
line = input().split()
(n, S) = (int(line[0]), int(line[1]))
for i in range(n):
	line = input().split()
	s.append(int(line[0]))
	a.append(int(line[1]))
	b.append(int(line[2]))
	if a[i] > b[i]:
		s1 += s[i]
	elif a[i] < b[i]:
		s2 += s[i]
	sum += s[i]
	ans += max(a[i], b[i]) * s[i]
	c.append(node(a[i] - b[i], i))
cnt = (sum + S - 1) // S
if (s1 + S - 1) // S + (s2 + S - 1) // S <= cnt:
	print(ans)
else:
	c.sort()
	s1 %= S
	s2 %= S
	for i in range(n):
		if c[i].x <= 0:
			f = i
			continue
		if not s1:
			break
		t = min(s[c[i].id], s1)
		a1 += t * c[i].x
		s1 -= t
	for i in range(f, -1, -1):
		if not c[i].x:
			continue
		if not s2:
			break
		t = min(s[c[i].id], s2)
		a2 -= t * c[i].x
		s2 -= t
	print(ans - min(a1, a2))


f = lambda : map(int, input().split())
(n, s) = f()
(u, v) = ([], [])
for i in range(n):
	(d, a, b) = f()
	if a > b:
		u.append([a, b, d])
	else:
		v.append([b, a, d])

def g(t):
	t.sort(key=lambda q: q[1] - q[0])
	m = sum((d for (a, b, d) in t))
	k = s * (m // s)
	n = m - k
	x = y = z = 0
	for (a, b, d) in t:
		if k >= d:
			k -= d
			z += d * a
		elif k:
			z += k * a
			x = (d - k) * a
			y = (d - k) * b
			k = 0
		else:
			x += d * a
			y += d * b
	return (x, y, z, n)
(a, b) = (g(u), g(v))
d = a[0] + b[0] if a[3] + b[3] > s else max(a[0] + b[1], a[1] + b[0])
print(a[2] + b[2] + d)


def cns(ts, s):
	if ts / s == int(ts / s):
		return ts
	else:
		return (int(ts / s) + 1) * s
(n, spp) = [int(i) for i in input().split()]
tsr = 0
da = [[] for i in range(100005)]
db = [[] for i in range(100005)]
sl = []
for i in range(n):
	sl.append([int(j) for j in input().split()])
	tsr += sl[i][0]
	if sl[i][1] > sl[i][2]:
		da[sl[i][1] - sl[i][2]].append(i)
	else:
		db[sl[i][2] - sl[i][1]].append(i)
tsa = cns(tsr, spp)
a1 = 0
c1 = 0
for i in range(100000, -1, -1):
	for j in da[i]:
		a1 += sl[j][0] * sl[j][1]
		c1 += sl[j][0]
c1r = cns(c1, spp) - c1
c2r = tsa - cns(c1, spp)
for i in range(100000, -1, -1):
	for j in db[i]:
		if sl[j][0] > c2r:
			a1 += c2r * sl[j][2]
			a1 += (sl[j][0] - c2r) * sl[j][1]
			c2r = 0
		else:
			a1 += sl[j][0] * sl[j][2]
			c2r -= sl[j][0]
a2 = 0
c2 = 0
for i in range(100000, -1, -1):
	for j in db[i]:
		a2 += sl[j][0] * sl[j][2]
		c2 += sl[j][0]
c2r = cns(c2, spp) - c2
c1r = tsa - cns(c2, spp)
for i in range(100000, -1, -1):
	for j in da[i]:
		if sl[j][0] > c1r:
			a2 += c1r * sl[j][1]
			a2 += (sl[j][0] - c1r) * sl[j][2]
			c1r = 0
		else:
			a2 += sl[j][0] * sl[j][1]
			c1r -= sl[j][0]
print(max(a1, a2))


(n, S) = map(int, input().split())
arr = []
suma = 0
happy = 0
sumb = 0
dif = []
for i in range(n):
	(c, a, b) = map(int, input().split())
	if a >= b:
		suma += c
		happy += a * c
	else:
		sumb += c
		happy += b * c
	dif.append((a - b, c))
dif.sort()
num = (suma + sumb - 1) // S + 1
if (suma - 1) // S + 1 + (sumb - 1) // S + 1 <= num:
	print(happy)
else:
	moda = suma % S
	modb = sumb % S
	for i in range(n):
		if dif[i][0] >= 0:
			ind = i
			break
	ans1 = happy
	ans2 = happy
	first = min(S - modb, moda)
	if first <= moda:
		now = ind
		ans1 = 0
		while first > 0:
			if dif[now][1] > first:
				ans1 += dif[now][0] * first
				first = 0
			else:
				ans1 += dif[now][0] * dif[now][1]
				first -= dif[now][1]
			now += 1
	second = min(S - moda, modb)
	if second <= modb:
		now = ind - 1
		ans2 = 0
		while second > 0:
			if dif[now][1] > second:
				ans2 -= dif[now][0] * second
				second = 0
			else:
				ans2 -= dif[now][0] * dif[now][1]
				second -= dif[now][1]
			now -= 1
	print(happy - min(ans1, ans2))


from math import ceil
(N, S) = input().split()
(N, S) = (int(N), int(S))
C = 0
pC = 0
nC = 0
cArr = []
for i in range(N):
	(s, a, b) = input().split()
	(s, a, b) = (int(s), int(a), int(b))
	C += s * b
	cArr.append((a - b, s))
	if a > b:
		pC += s
	else:
		nC += s
cArr.sort(key=lambda k: -k[0])
tP = int(ceil((nC + pC) / S))
nP = int(pC / S)
hAns = C
sItr = nP * S
itr = 0
while sItr > 0 and itr < N:
	si = min(cArr[itr][1], sItr)
	hAns += si * cArr[itr][0]
	sItr -= si
	itr += 1
hAns2 = C
nP = int(pC / S) + 1
sItr = nP * S
e = S * (tP - nP) - nC
itr = 0
while itr < N and cArr[itr][0] > 0:
	si = min(cArr[itr][1], sItr)
	hAns2 += si * cArr[itr][0]
	sItr -= si
	itr += 1
if e < 0:
	sItr = -e
	while sItr > 0 and itr < N:
		si = min(cArr[itr][1], sItr)
		hAns2 += si * cArr[itr][0]
		sItr -= si
		itr += 1
print(max(hAns, hAns2))