//by yjz
#include<bits/stdc++.h>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
#define bged(v) (v).begin(),(v).end()
#define foreach(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
typedef long long ll;
const int Imx=2147483647;
const ll Lbig=2e18;
const int mod=1e9+7;
//My i/o stream
struct fastio
{
	char s[100000];
	int it,len;
	fastio(){it=len=0;}
	inline char get()
	{
		if(it<len)return s[it++];it=0;
		len=fread(s,1,100000,stdin);
		if(len==0)return EOF;else return s[it++];
	}
	bool notend()
	{
		char c=get();
		while(c==' '||c=='\n')c=get();
		if(it>0)it--;
		return c!=EOF;
	}
}_buff;
#define geti(x) x=getnum()
#define getii(x,y) geti(x),geti(y)
#define getiii(x,y,z) getii(x,y),geti(z)
#define puti(x) putnum(x),putchar(' ')
#define putii(x,y) puti(x),puti(y)
#define putiii(x,y,z) putii(x,y),puti(z)
#define putsi(x) putnum(x),putchar('\n')
#define putsii(x,y) puti(x),putsi(y)
#define putsiii(x,y,z) putii(x,y),putsi(z)
inline ll getnum()
{
	ll r=0;bool ng=0;char c;c=_buff.get();
	while(c!='-'&&(c<'0'||c>'9'))c=_buff.get();
	if(c=='-')ng=1,c=_buff.get();
	while(c>='0'&&c<='9')r=r*10+c-'0',c=_buff.get();
	return ng?-r:r;
}
template<class T> inline void putnum(T x)
{
	if(x<0)putchar('-'),x=-x;
	register short a[20]={},sz=0;
	while(x)a[sz++]=x%10,x/=10;
	if(sz==0)putchar('0');
	for(int i=sz-1;i>=0;i--)putchar('0'+a[i]);
}
inline char getreal(){char c=_buff.get();while(c==' '||c=='\n')c=_buff.get();return c;}
int n;
ll s,a[100111],b[100111],c[100111];
ll cntf,sum;
set<pair<ll,ll> >st,st2;
ll calc(ll y)
{
//	cerr<<"calc:"<<y<<endl;
	st.clear();
	for(int i=1;i<=n;i++)
	{
		st.insert(MP(b[i]-c[i],a[i]));
	}
	ll lft=y;
	ll ans=sum;
//	st2.clear();
	while(st.size()>0)
	{
		ll p=st.begin()->FF,c=st.begin()->SS;
		st.erase(st.begin());
		ll t=min(c,lft);
//		if(t>0)st2.insert(MP(-p,t));
//		cerr<<"add:"<<p<<" "<<t<<endl;
		ans+=t*(-p);
		lft-=t;
	}
//	cerr<<"ans="<<ans<<endl;
	return ans;
}
int main()
{
	getii(n,s);
	ll tot=0;
	ll t=0;
	for(int i=1;i<=n;i++)
	{
		getiii(a[i],b[i],c[i]);
		sum+=a[i]*b[i];
		tot+=a[i];
		if(b[i]<c[i])
		{
			t+=a[i];
		}
	}
	cntf=tot;
	tot=(tot+s-1)/s;
	cntf=tot*s-cntf;
//	cerr<<"tot="<<tot<<endl;
//	cerr<<cntf<<endl;
	ll ans=calc((t/s)*s);
	if(t/s+1<=tot)ans=max(ans,calc((t/s)*s+max(0ll,max(t%s,s-cntf))));
	cout<<ans<<endl;
	return 0;
}


//by yjz
#include<bits/stdc++.h>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
#define bged(v) (v).begin(),(v).end()
#define foreach(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
typedef long long ll;
const int Imx=2147483647;
const ll Lbig=2e18;
const int mod=1e9+7;
//My i/o stream
struct fastio
{
	char s[100000];
	int it,len;
	fastio(){it=len=0;}
	inline char get()
	{
		if(it<len)return s[it++];it=0;
		len=fread(s,1,100000,stdin);
		if(len==0)return EOF;else return s[it++];
	}
	bool notend()
	{
		char c=get();
		while(c==' '||c=='\n')c=get();
		if(it>0)it--;
		return c!=EOF;
	}
}_buff;
#define geti(x) x=getnum()
#define getii(x,y) geti(x),geti(y)
#define getiii(x,y,z) getii(x,y),geti(z)
#define puti(x) putnum(x),putchar(' ')
#define putii(x,y) puti(x),puti(y)
#define putiii(x,y,z) putii(x,y),puti(z)
#define putsi(x) putnum(x),putchar('\n')
#define putsii(x,y) puti(x),putsi(y)
#define putsiii(x,y,z) putii(x,y),putsi(z)
inline ll getnum()
{
	ll r=0;bool ng=0;char c;c=_buff.get();
	while(c!='-'&&(c<'0'||c>'9'))c=_buff.get();
	if(c=='-')ng=1,c=_buff.get();
	while(c>='0'&&c<='9')r=r*10+c-'0',c=_buff.get();
	return ng?-r:r;
}
template<class T> inline void putnum(T x)
{
	if(x<0)putchar('-'),x=-x;
	register short a[20]={},sz=0;
	while(x)a[sz++]=x%10,x/=10;
	if(sz==0)putchar('0');
	for(int i=sz-1;i>=0;i--)putchar('0'+a[i]);
}
inline char getreal(){char c=_buff.get();while(c==' '||c=='\n')c=_buff.get();return c;}
int n;
ll s,a[100111],b[100111],c[100111];
ll cntf,sum;
set<pair<ll,ll> >st,st2;
ll calc(ll y)
{
//	cerr<<"calc:"<<y<<endl;
	st.clear();
	for(int i=1;i<=n;i++)
	{
		st.insert(MP(b[i]-c[i],a[i]));
	}
	ll lft=y*s;
	ll ans=sum;
	st2.clear();
	while(st.size()>0)
	{
		ll p=st.begin()->FF,c=st.begin()->SS;
		st.erase(st.begin());
		ll t=min(c,lft);
		if(t>0)st2.insert(MP(-p,t));
//		cerr<<"add:"<<p<<" "<<t<<endl;
		ans+=t*(-p);
		lft-=t;
	}
	for(int i=0;i<cntf;i++)
	{
		if(st2.size()==0)continue;
		ll p=st2.begin()->FF,c=st2.begin()->SS;
//		cerr<<"p="<<p<<" c="<<c<<endl;
		if(p<0)
		{
			if(c>0)
			{
				ans-=p;

//				cerr<<"p="<<p<<" c="<<c<<endl;
				c--;
				st2.erase(st2.begin());
				if(c>0)st2.insert(MP(p,c));
			}
		}
	}
//	cerr<<"ans="<<ans<<endl;
	return ans;
}
int main()
{
	getii(n,s);
	ll tot=0;
	ll t=0;
	for(int i=1;i<=n;i++)
	{
		getiii(a[i],b[i],c[i]);
		sum+=a[i]*b[i];
		tot+=a[i];
		if(b[i]<c[i])
		{
			t+=a[i];
		}
	}
	cntf=tot;
	tot=(tot+s-1)/s;
	cntf=tot*s-cntf;
//	cerr<<"tot="<<tot<<endl;
//	cerr<<cntf<<endl;
	ll ans=calc(t/s);
	if(t/s+1<=tot)ans=max(ans,calc(t/s+1));
	cout<<ans<<endl;
	return 0;
}


//by yjz
#include<bits/stdc++.h>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
#define bged(v) (v).begin(),(v).end()
#define foreach(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
typedef long long ll;
const int Imx=2147483647;
const ll Lbig=2e18;
const int mod=1e9+7;
//My i/o stream
struct fastio
{
	char s[100000];
	int it,len;
	fastio(){it=len=0;}
	inline char get()
	{
		if(it<len)return s[it++];it=0;
		len=fread(s,1,100000,stdin);
		if(len==0)return EOF;else return s[it++];
	}
	bool notend()
	{
		char c=get();
		while(c==' '||c=='\n')c=get();
		if(it>0)it--;
		return c!=EOF;
	}
}_buff;
#define geti(x) x=getnum()
#define getii(x,y) geti(x),geti(y)
#define getiii(x,y,z) getii(x,y),geti(z)
#define puti(x) putnum(x),putchar(' ')
#define putii(x,y) puti(x),puti(y)
#define putiii(x,y,z) putii(x,y),puti(z)
#define putsi(x) putnum(x),putchar('\n')
#define putsii(x,y) puti(x),putsi(y)
#define putsiii(x,y,z) putii(x,y),putsi(z)
inline ll getnum()
{
	ll r=0;bool ng=0;char c;c=_buff.get();
	while(c!='-'&&(c<'0'||c>'9'))c=_buff.get();
	if(c=='-')ng=1,c=_buff.get();
	while(c>='0'&&c<='9')r=r*10+c-'0',c=_buff.get();
	return ng?-r:r;
}
template<class T> inline void putnum(T x)
{
	if(x<0)putchar('-'),x=-x;
	register short a[20]={},sz=0;
	while(x)a[sz++]=x%10,x/=10;
	if(sz==0)putchar('0');
	for(int i=sz-1;i>=0;i--)putchar('0'+a[i]);
}
inline char getreal(){char c=_buff.get();while(c==' '||c=='\n')c=_buff.get();return c;}
int n;
ll s,a[100111],b[100111],c[100111];
ll cntf,sum;
priority_queue<pair<ll,ll> >pq;
ll calc(ll y)
{
//	cerr<<"calc:"<<y<<endl;
	while(!pq.empty())pq.pop();
	for(int i=1;i<=n;i++)
	{
		pq.push(MP(c[i]-b[i],a[i]));
	}
	ll lft=y;
	ll ans=sum;
//	st2.clear();
	while(!pq.empty())
	{
		ll p=pq.top().FF,c=pq.top().SS;
		pq.pop();
		ll t=min(c,lft);
//		if(t>0)st2.insert(MP(-p,t));
//		cerr<<"add:"<<p<<" "<<t<<endl;
		ans+=t*(p);
		lft-=t;
	}
//	cerr<<"ans="<<ans<<endl;
	return ans;
}
int main()
{
	getii(n,s);
	ll tot=0;
	ll t=0;
	for(int i=1;i<=n;i++)
	{
		getiii(a[i],b[i],c[i]);
		sum+=a[i]*b[i];
		tot+=a[i];
		if(b[i]<c[i])
		{
			t+=a[i];
		}
	}
	cntf=tot;
	tot=(tot+s-1)/s;
	cntf=tot*s-cntf;
//	cerr<<"tot="<<tot<<endl;
//	cerr<<cntf<<endl;
	ll ans=calc((t/s)*s);
	if(t/s+1<=tot)ans=max(ans,calc((t/s)*s+max(0ll,max(t%s,s-cntf))));
	cout<<ans<<endl;
	return 0;
}


//by yjz
#include<bits/stdc++.h>
using namespace std;
#define FF first
#define SS second
#define PB push_back
#define MP make_pair
#define bged(v) (v).begin(),(v).end()
#define foreach(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
typedef long long ll;
const int Imx=2147483647;
const ll Lbig=2e18;
const int mod=1e9+7;
//My i/o stream
struct fastio
{
	char s[100000];
	int it,len;
	fastio(){it=len=0;}
	inline char get()
	{
		if(it<len)return s[it++];it=0;
		len=fread(s,1,100000,stdin);
		if(len==0)return EOF;else return s[it++];
	}
	bool notend()
	{
		char c=get();
		while(c==' '||c=='\n')c=get();
		if(it>0)it--;
		return c!=EOF;
	}
}_buff;
#define geti(x) x=getnum()
#define getii(x,y) geti(x),geti(y)
#define getiii(x,y,z) getii(x,y),geti(z)
#define puti(x) putnum(x),putchar(' ')
#define putii(x,y) puti(x),puti(y)
#define putiii(x,y,z) putii(x,y),puti(z)
#define putsi(x) putnum(x),putchar('\n')
#define putsii(x,y) puti(x),putsi(y)
#define putsiii(x,y,z) putii(x,y),putsi(z)
inline ll getnum()
{
	ll r=0;bool ng=0;char c;c=_buff.get();
	while(c!='-'&&(c<'0'||c>'9'))c=_buff.get();
	if(c=='-')ng=1,c=_buff.get();
	while(c>='0'&&c<='9')r=r*10+c-'0',c=_buff.get();
	return ng?-r:r;
}
template<class T> inline void putnum(T x)
{
	if(x<0)putchar('-'),x=-x;
	register short a[20]={},sz=0;
	while(x)a[sz++]=x%10,x/=10;
	if(sz==0)putchar('0');
	for(int i=sz-1;i>=0;i--)putchar('0'+a[i]);
}
inline char getreal(){char c=_buff.get();while(c==' '||c=='\n')c=_buff.get();return c;}
int n;
ll s,a[100111],b[100111],c[100111];
ll cntf,sum;
set<pair<ll,ll> >st,st2;
ll calc(ll y)
{
//	cerr<<"calc:"<<y<<endl;
	st.clear();
	for(int i=1;i<=n;i++)
	{
		st.insert(MP(b[i]-c[i],a[i]));
	}
	ll lft=y;
	ll ans=sum;
//	st2.clear();
	while(st.size()>0)
	{
		ll p=st.begin()->FF,c=st.begin()->SS;
		st.erase(st.begin());
		ll t=min(c,lft);
//		if(t>0)st2.insert(MP(-p,t));
//		cerr<<"add:"<<p<<" "<<t<<endl;
		ans+=t*(-p);
		lft-=t;
	}
//	cerr<<"ans="<<ans<<endl;
	return ans;
}
int main()
{
	getii(n,s);
	ll tot=0;
	ll t=0;
	for(int i=1;i<=n;i++)
	{
		getiii(a[i],b[i],c[i]);
		sum+=a[i]*b[i];
		tot+=a[i];
		if(b[i]<c[i])
		{
			t+=a[i];
		}
	}
	cntf=tot;
	tot=(tot+s-1)/s;
	cntf=tot*s-cntf;
//	cerr<<"tot="<<tot<<endl;
//	cerr<<cntf<<endl;
	ll ans=calc((t/s)*s);
	if(t/s+1<=tot)ans=max(ans,calc((t/s)*s+max(t%s,s-cntf)));
	cout<<ans<<endl;
	return 0;
}


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

#define st first
#define nd second
#define mp make_pair
#define pb push_back
#define cl(x, v) memset((x), (v), sizeof(x))

#define db(x) cerr << #x << " == " << x << endl
#define dbs(x) cerr << x << endl
#define _ << ", " <<

typedef long long ll;
typedef long double ld;

typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;

const ld EPS = 1e-9, PI = acos(-1.);
const int INF = 0x3f3f3f3f, MOD = 1e9+7;
const int N = 1e5+5;

ll n, s, a[N], b[N], c[N], id[N], sm, pz, ans;

ll slv(ll k) {
  ll aa = k * s, ab = (pz - k) * s;
  ll ans = 0;

  for(int j=0, i; j<n; ++j) {
    i = id[j];

    ll pa, pb;
    if (a[i] > b[i]) {
      pa = min(aa, c[i]);
      pb = c[i] - pa;
    } else {
      pb = min(ab, c[i]);
      pa = c[i] - pb;
    }

    aa -= pa;
    ab -= pb;
    ll dlt = pa*a[i] + pb*b[i];
    ans += dlt;
  }

  return ans;
}

bool cp(int i, int j) { return abs(a[i] - b[i]) > abs(a[j] - b[j]); }

int main() {
  scanf("%lld%lld", &n, &s);
  for(int i=0; i<n; ++i) scanf("%lld%lld%lld", c+i, a+i, b+i), sm += c[i], id[i] = i;

  sort(id, id+n, cp);

  pz = (sm + s - 1) / s;

  ll l = 0, r = pz;
  while(l < r) {
    ll m = (l+r) / 2;
    if (slv(m) < slv(m+1)) l = m+1;
    else r = m;
  }

  printf("%lld\n", slv(r));
  return 0;
}


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

#define st first
#define nd second
#define mp make_pair
#define pb push_back
#define cl(x, v) memset((x), (v), sizeof(x))

#define db(x) cerr << #x << " == " << x << endl
#define dbs(x) cerr << x << endl
#define _ << ", " <<

typedef long long ll;
typedef long double ld;

typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;

const ld EPS = 1e-9, PI = acos(-1.);
const int INF = 0x3f3f3f3f, MOD = 1e9+7;
const int N = 1e5+5;

ll n, s, a[N], b[N], c[N], id[N], sm, pz, ans;

ll slv(int k) {
  ll aa = k * s, ab = (pz - k) * s;
  ll ans = 0;

  for(int j=0, i; j<n; ++j) {
    i = id[j];

    ll pa, pb;
    if (a[i] > b[i]) {
      pa = min(aa, c[i]);
      pb = c[i] - pa;
    } else {
      pb = min(ab, c[i]);
      pa = c[i] - pb;
    }

    aa -= pa;
    ab -= pb;
    ll dlt = pa*a[i] + pb*b[i];
    ans += dlt;
  }

  return ans;
}

bool cp(int i, int j) { return abs(a[i] - b[i]) > abs(a[j] - b[j]); }

int main() {
  scanf("%lld%lld", &n, &s);
  for(int i=0; i<n; ++i) scanf("%lld%lld%lld", c+i, a+i, b+i), sm += c[i], id[i] = i;

  sort(id, id+n, cp);

  pz = (sm + s - 1) / s;

  /*
  ans = 0;
  for(int i=0; i<=pz; ++i) ans = max(ans, slv(i));
  */

  ll l = 0, r = pz;
  while(l+5 < r) {
    printf("%lld %lld\n", l, r);
    int m1 = (2*l+r) / 3, m2 = (l+ 2*r) / 3;
    if (slv(m1) < slv(m2)) l = m1;
    else r = m2;
  }

  for(int i=l; i<=r; ++i) ans = max(ans, slv(i));

  printf("%lld\n", ans);
  return 0;
}


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

#define st first
#define nd second
#define mp make_pair
#define pb push_back
#define cl(x, v) memset((x), (v), sizeof(x))

#define db(x) cerr << #x << " == " << x << endl
#define dbs(x) cerr << x << endl
#define _ << ", " <<

typedef long long ll;
typedef long double ld;

typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;

const ld EPS = 1e-9, PI = acos(-1.);
const int INF = 0x3f3f3f3f, MOD = 1e9+7;
const int N = 1e5+5;

ll n, s, a[N], b[N], c[N], id[N], sm, pz, ans;

ll slv(int k) {
  ll aa = k * s, ab = (pz - k) * s;
  ll ans = 0;

  for(int j=0, i; j<n; ++j) {
    i = id[j];

    ll pa, pb;
    if (a[i] > b[i]) {
      pa = min(aa, c[i]);
      pb = c[i] - pa;
    } else {
      pb = min(ab, c[i]);
      pa = c[i] - pb;
    }

    aa -= pa;
    ab -= pb;
    ll dlt = pa*a[i] + pb*b[i];
    ans += dlt;
  }

  return ans;
}

bool cp(int i, int j) { return abs(a[i] - b[i]) > abs(a[j] - b[j]); }

int main() {
  scanf("%lld%lld", &n, &s);
  for(int i=0; i<n; ++i) scanf("%lld%lld%lld", c+i, a+i, b+i), sm += c[i], id[i] = i;

  sort(id, id+n, cp);

  pz = (sm + s - 1) / s;

  ll l = 0, r = pz;
  while(l < r) {
    int m = (l+r) / 2;
    if (slv(m) < slv(m+1)) l = m+1;
    else r = m;
  }

  printf("%lld\n", slv(r));
  return 0;
}


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

#define st first
#define nd second
#define mp make_pair
#define pb push_back
#define cl(x, v) memset((x), (v), sizeof(x))

#define db(x) cerr << #x << " == " << x << endl
#define dbs(x) cerr << x << endl
#define _ << ", " <<

typedef long long ll;
typedef long double ld;

typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;

const ld EPS = 1e-9, PI = acos(-1.);
const int INF = 0x3f3f3f3f, MOD = 1e9+7;
const int N = 1e5+5;

ll n, s, a[N], b[N], c[N], id[N], sm, pz, ans;

ll slv(int k) {
  ll aa = k * s, ab = (pz - k) * s;
  ll ans = 0;

  for(int j=0, i; j<n; ++j) {
    i = id[j];

    ll pa, pb;
    if (a[i] > b[i]) {
      pa = min(aa, c[i]);
      pb = c[i] - pa;
    } else {
      pb = min(ab, c[i]);
      pa = c[i] - pb;
    }

    aa -= pa;
    ab -= pb;
    ll dlt = pa*a[i] + pb*b[i];
    ans += dlt;
  }

  return ans;
}

bool cp(int i, int j) { return abs(a[i] - b[i]) > abs(a[j] - b[j]); }

int main() {
  scanf("%lld%lld", &n, &s);
  for(int i=0; i<n; ++i) scanf("%lld%lld%lld", c+i, a+i, b+i), sm += c[i], id[i] = i;

  sort(id, id+n, cp);

  pz = (sm + s - 1) / s;

  ans = 0;
  for(int i=0; i<=pz; ++i) ans = max(ans, slv(i));

  /*
  ll l = 0, r = pz;
  while(l+5 < r) {
    printf("%lld %lld\n", l, r);
    int m1 = (2*l+r) / 3, m2 = (l+ 2*r) / 3;
    if (slv(m1) < slv(m2)) l = m1;
    else r = m2;
  }

  for(int i=l; i<=r; ++i) ans = max(ans, slv(i));
  */

  printf("%lld\n", ans);
  return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define ll long long
#define db long double
#define ii pair<int,int>
#define vi vector<int>
#define fi first
#define se second
#define sz(a) (int)(a).size()
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define mp make_pair
#define FN(i, n) for (int i = 0; i < (int)(n); ++i)
#define FEN(i,n) for (int i = 1;i <= (int)(n); ++i)
#define rep(i,a,b) for(i=a;i<b;i++)
#define repv(i,a,b) for(i=b-1;i>=a;i--)
#define SET(A, val) memset(A, val, sizeof(A))
typedef tree<int ,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set ;
// order_of_key (val): returns the no. of values less than val
// find_by_order (k): returns the kth largest element.(0-based)
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
	template <typename Arg1>
	void __f(const char* name, Arg1&& arg1){
		cerr << name << " : " << arg1 << std::endl;
	}
	template <typename Arg1, typename... Args>
	void __f(const char* names, Arg1&& arg1, Args&&... args){
		const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
	}
#else
#define trace(...)
#endif
ll solve(vi a,vi b,vi s,int N,int slice,vi &allowed)
{
	ll ans = 0, more = 0 ;
	vector<ii> c(N) ; FN(i,N) c[i].fi = a[i] - b[i], c[i].se = s[i], ans += (ll)b[i] * (ll)s[i] ;
	sort(all(c),greater<ii>()) ;
	vector<ll> pre(N), cost(N) ;
	// trace(ans) ;
	// for(auto it : c) cout<<it.fi<<" "<<it.se<<" | " ; cout<<endl ;
	pre[0] = c[0].se ; cost[0] = (ll) c[0].se * (ll) c[0].fi ;
	FEN(i,N-1) pre[i] = pre[i-1] + c[i].se ;
	FEN(i,N-1) cost[i] = cost[i-1] + (ll) c[i].se * (ll) c[i].fi ;
	FN(i,N)
	{
		// if(c[i].fi < 0) break ;
		ll mod = pre[i]%slice ;
		// trace(i,pre[i],mod) ;
		int y = lower_bound(all(allowed),mod) - allowed.begin() ;
		if(allowed[y] == mod)
		{
			more = max(more,cost[i]) ;
			// trace("inside",more) ;
			continue ;
		}
		ll req = pre[i] + (allowed[y] - mod) ;
		int x = lower_bound(all(pre),req) - pre.begin() ;
		if(x < N) more = max(more,cost[x]-(pre[x]-req)*(ll)c[x].fi) ;

		req = pre[i] - (mod - allowed[y-1]) ;
		x = lower_bound(all(pre),req) - pre.begin() ;
		more = max(more,cost[x]-(pre[x]-req)*(ll)c[x].fi) ;
	}
	assert(more >= 0 ) ;
	return ans + more ;
}
int main()
{
	std::ios::sync_with_stdio(false);
	cin.tie(NULL) ; cout.tie(NULL) ;
	int N, slice ; cin>>N>>slice ;
	vi a(N), b(N), s(N) ;
	FN(i,N) cin>>s[i]>>a[i]>>b[i] ;
	ll tot = 0 ; FN(i,N) tot += s[i] ;
	vi allowed ;
	FN(i,slice) if( i%slice == 0 || (tot-i)%slice == 0 || (i%slice + (tot-i)%slice) > slice) allowed.pb(i) ;
	allowed.pb(slice) ;
	// for(auto it:allowed) cout<<it<<" " ; cout<<endl ;
	cout<<solve(a,b,s,N,slice,allowed)<<endl ;
	return 0 ;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define ll long long
#define db long double
#define ii pair<int,int>
#define vi vector<int>
#define fi first
#define se second
#define sz(a) (int)(a).size()
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define mp make_pair
#define FN(i, n) for (int i = 0; i < (int)(n); ++i)
#define FEN(i,n) for (int i = 1;i <= (int)(n); ++i)
#define rep(i,a,b) for(i=a;i<b;i++)
#define repv(i,a,b) for(i=b-1;i>=a;i--)
#define SET(A, val) memset(A, val, sizeof(A))
typedef tree<int ,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set ;
// order_of_key (val): returns the no. of values less than val
// find_by_order (k): returns the kth largest element.(0-based)
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
	template <typename Arg1>
	void __f(const char* name, Arg1&& arg1){
		cerr << name << " : " << arg1 << std::endl;
	}
	template <typename Arg1, typename... Args>
	void __f(const char* names, Arg1&& arg1, Args&&... args){
		const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
	}
#else
#define trace(...)
#endif
ll solve(vi a,vi b,vi s,int N,int slice)
{
	ll ans = 0, more = 0 ;
	vector<ii> c(N) ; FN(i,N) c[i].fi = a[i] - b[i], c[i].se = s[i], ans += (ll)b[i] * (ll)s[i] ;
	sort(all(c)) ;
	reverse(all(c)) ;
	vector<ll> pre(N),cost(N) ;
	pre[0] = c[0].se ; cost[0] = (ll) c[0].se * (ll) c[0].fi ;
	FEN(i,N-1) pre[i] = pre[i-1] + c[i].se ;
	FEN(i,N-1) cost[i] = cost[i-1] + (ll) c[i].se * (ll) c[i].fi ;
	FN(i,N)
	{
		if(pre[i]%slice == 0) more = max(more,cost[i]) ;
		else
		{
			ll rem = pre[i]%slice ;
			ll req = pre[i] - rem ;
			int x = lower_bound(all(pre),req) - pre.begin() ;
			more = max(more,cost[x] - (pre[x]-req)*c[x].fi) ;

			ll add = slice - rem ;
			req = pre[i] + add ;
			x = lower_bound(all(pre),req) - pre.begin() ;
			if(x < N) more = max(more,cost[x]-(pre[x]-req)*c[x].fi) ;
		}
	}
	return ans + more ;
}
int main()
{
	std::ios::sync_with_stdio(false);
	cin.tie(NULL) ; cout.tie(NULL) ;
	int N, slice ; cin>>N>>slice ;
	vi a(N), b(N), s(N) ;
	FN(i,N) cin>>s[i]>>a[i]>>b[i] ;
	cout<<max(solve(a,b,s,N,slice),solve(b,a,s,N,slice))<<endl ;
	return 0 ;
}


#include <bits/stdc++.h>

typedef long long ll;
using namespace std;

#define all(x) x.begin(), x.end()
#define f(i,a,b) for(int i = (a); i <= (b); i++)
#define fd(i,a,b) for(int i = (a); i >= (b); i--)
#define mp make_pair
#define faster_io() ios_base::sync_with_stdio(false)
#define pb push_back
#define pii pair<ll,ll>
#define SZ(x) ((int)x.size())
#define vii vector<pair<ll,ll>>

const int INF = 2000000005;
const ll INFLL = 1000000000000000002ll;
const ll MOD = 1000000007;

inline ll min(ll a, ll b, ll c){return min(min(a,b),c);}
inline ll min(ll a, ll b, ll c, ll d){return min(min(min(a,b),c),d);}
inline ll max(ll a, ll b, ll c){return max(max(a,b),c);}
inline ll max(ll a, ll b, ll c, ll d){return max(max(max(a,b),c),d);}

// -------------------------------------------------------------------------------------------------------------

struct Student
{
    int eat, a, b;
    Student(int _eat = 0, int _a = 0, int _b = 0) : eat(_eat), a(_a), b(_b) {};
    friend bool operator < (Student s1, Student s2)
    {
        return s1.b - s1.a < s2.b - s2.a;
    }
};

int N, S;
ll P, Tot = 0;
Student A[100005];

ll solve(ll a, ll b)
{
    if(a < 0 || b < 0) return 0;
    a *= S, b *= S;
    ll ret = 0;
    f(i,1,N)
    {
        ll eat_a = min((ll) A[i].eat, a);
        a -= eat_a;
        ret += eat_a * A[i].a;
        ll eat_b = A[i].eat - eat_a;
        b -= eat_b;
        ret += eat_b * A[i].b;
    }
    return ret;
}

int main()
{
    cin >> N >> S;
    f(i,1,N) scanf("%d %d %d", &A[i].eat, &A[i].a, &A[i].b);
    f(i,1,N) Tot += A[i].eat;
    ll rem = S - Tot%S;
    if(rem == S) rem = 0;
    N++;
    A[N].eat = rem;
    sort(A+1,A+N+1);
    Tot = 0;
    f(i,1,N) Tot += A[i].eat;
    P = Tot/S;
    int ta = 0;
    f(i,1,N) if(A[i].a > A[i].b) ta++;
    ll ans = 0;
    f(a,ta-1,ta+1) ans = max(ans, solve(a,P-a));
    cout << ans;
}


#include <bits/stdc++.h>

typedef long long ll;
using namespace std;

#define all(x) x.begin(), x.end()
#define f(i,a,b) for(int i = (a); i <= (b); i++)
#define fd(i,a,b) for(int i = (a); i >= (b); i--)
#define mp make_pair
#define faster_io() ios_base::sync_with_stdio(false)
#define pb push_back
#define pii pair<ll,ll>
#define SZ(x) ((int)x.size())
#define vii vector<pair<ll,ll>>

const int INF = 2000000005;
const ll INFLL = 1000000000000000002ll;
const ll MOD = 1000000007;

inline ll min(ll a, ll b, ll c){return min(min(a,b),c);}
inline ll min(ll a, ll b, ll c, ll d){return min(min(min(a,b),c),d);}
inline ll max(ll a, ll b, ll c){return max(max(a,b),c);}
inline ll max(ll a, ll b, ll c, ll d){return max(max(max(a,b),c),d);}

// -------------------------------------------------------------------------------------------------------------

struct Student
{
    int eat, a, b;
    Student(int _eat = 0, int _a = 0, int _b = 0) : eat(_eat), a(_a), b(_b) {};
    friend bool operator < (Student s1, Student s2)
    {
        return s1.b - s1.a < s2.b - s2.a;
    }
};

int N, S;
ll P, Tot = 0;
Student A[100005];

ll solve(ll a, ll b)
{
    if(a < 0 || b < 0) return 0;
    a *= S, b *= S;
    ll ret = 0;
    f(i,1,N)
    {
        ll eat_a = min((ll) A[i].eat, a);
        a -= eat_a;
        ret += eat_a * A[i].a;
        ll eat_b = A[i].eat - eat_a;
        b -= eat_b;
        ret += eat_b * A[i].b;
    }
    return ret;
}

int main()
{
    cin >> N >> S;
    f(i,1,N) scanf("%d %d %d", &A[i].eat, &A[i].a, &A[i].b);
    f(i,1,N) Tot += A[i].eat;
    ll rem = S - Tot%S;
    if(rem == S) rem = 0;
    N++;
    A[N].eat = rem;
    sort(A+1,A+N+1);
    Tot = 0;
    f(i,1,N) Tot += A[i].eat;
    P = Tot/S;
    ll ta = 0;
    f(i,1,N) if(A[i].a > A[i].b) ta += A[i].eat;
    ta /= S;
    ll ans = 0;
    for(ll a = ta-5; a <= ta+5; a++) ans = max(ans, solve(a,P-a));
    cout << ans;
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
map<pair<ll, ll>, ll> d;
vector<pair<ll, ll> > ar;

ll get(ll a) {
	int it = 0;
	ll sum = 0, pcsa = S * a, last = 0;
	while (pcsa && it < ar.size()) {
		//cout << it << ' ' << pcsa << endl;
		if (pcsa > d[ar[it]]) {
			sum += ar[it].f * d[ar[it]];
			pcsa -= d[ar[it++]];
		}
		else {
			last = d[ar[it]] - pcsa;
			sum += ar[it].f * pcsa;
			pcsa = 0;
			break;
		}
	}
	if (it < ar.size())
		sum += ar[it].s * last;
	for (int i = it + 1; i < ar.size(); ++i)
		sum += ar[i].s * d[ar[i]];
	//cout << "Pizzas: " << a << ' ' << sum << endl;
	return sum;
}

bool cmp(pair<int, int> a, pair<int, int> b) {
	if (a.s - a.f == b.s - b.f)
		return a.f > b.f;
	return a.s - a.f < b.s - b.f;
}

int main() {
	ios_base::sync_with_stdio(false);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	for (int i = 0; i < n; ++i) {
		int s;
		pair<ll, ll> t;
		cin >> s >> t.f >> t.s;
		sum += s;
		d[t] += s;
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S - sum)
		d[{0, 0}] += pzs * S - sum;
	for (auto i : d) {
		ar.pb(i.f);
	}
	sort(ar.begin(), ar.end(), cmp);
	//get(0);
	//get(1);
	ll ans = 0;
	ll l = 0, r = pzs;
	while (r - l > 1) {
		ll m = (l + r) / 2;
		if (get(m) < get(m + 1))
			l = m;
		else
			r = m;
	}
	for (; l <= min(r, pzs); ++l)
		chkmax(ans, get(l));
	cout << ans;
	return 0;
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
map<pair<ll, ll>, ll> d;
vector<pair<ll, ll> > ar;

ll get(ll a) {
	int it = 0;
	ll sum = 0, pcsa = S * a, last = 0;
	while (pcsa && it < ar.size()) {
		//cout << it << ' ' << pcsa << endl;
		if (pcsa > d[ar[it]]) {
			sum += ar[it].f * d[ar[it]];
			pcsa -= d[ar[it++]];
		}
		else {
			last = d[ar[it]] - pcsa;
			sum += ar[it].f * pcsa;
			pcsa = 0;
		}
	}
	if (it < ar.size())
		sum += ar[it].s * last;
	for (int i = it + 1; i < ar.size(); ++i)
		sum += ar[i].s * d[ar[i]];
	//cout << "Pizzas: " << a << ' ' << sum << endl;
	return sum;
}

bool cmp(pair<int, int> a, pair<int, int> b) {
	if (a.s - a.f == b.s - b.f)
		return a.f > b.f;
	return a.s - a.f < b.s - b.f;
}

int main() {
	ios_base::sync_with_stdio(false);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	for (int i = 0; i < n; ++i) {
		int s;
		pair<ll, ll> t;
		cin >> s >> t.f >> t.s;
		sum += s;
		d[t] += s;
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S - sum)
		d[{0, 0}] += pzs * S - sum;
	for (auto i : d) {
		ar.pb(i.f);
	}
	sort(ar.begin(), ar.end(), cmp);
	//get(0);
	//get(1);
	ll ans = 0;
	ll l = 0, r = pzs;
	while (r - l > 1) {
		ll m = (l + r) / 2;
		if (get(m) < get(m + 1))
			l = m;
		else
			r = m;
	}
	if (l < pzs)
		cout << max(get(l), get(l + 1));
	else
		cout << get(l);
	return 0;
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
map<pair<ll, ll>, ll> d;
vector<pair<ll, ll> > ar;

ll get(ll a) {
	int it = 0;
	ll sum = 0, pcsa = S * a, last = 0;
	while (pcsa && it < ar.size()) {
		//cout << it << ' ' << pcsa << endl;
		if (pcsa > d[ar[it]]) {
			sum += ar[it].f * d[ar[it]];
			pcsa -= d[ar[it++]];
		}
		else {
			last = d[ar[it]] - pcsa;
			sum += ar[it].f * pcsa;
			pcsa = 0;
		}
	}
	if (it < ar.size())
		sum += ar[it].s * last;
	for (int i = it + 1; i < ar.size(); ++i)
		sum += ar[i].s * d[ar[i]];
	//cout << "Pizzas: " << a << ' ' << sum << endl;
	return sum;
}

bool cmp(pair<int, int> a, pair<int, int> b) {
	if (a.s - a.f == b.s - b.f)
		return a.f > b.f;
	return a.s - a.f < b.s - b.f;
}

int main() {
	ios_base::sync_with_stdio(false);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	for (int i = 0; i < n; ++i) {
		int s;
		pair<ll, ll> t;
		cin >> s >> t.f >> t.s;
		sum += s;
		d[t] += s;
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S - sum)
		d[{0, 0}] += pzs * S - sum;
	for (auto i : d) {
		ar.pb(i.f);
	}
	sort(ar.begin(), ar.end(), cmp);
	//get(0);
	//get(1);
	ll ans = 0;
	ll l = 0, r = pzs;
	while (r - l > 3) {
		ll m1 = l + (r - l) / 3, m2 = l + (r - l) / 3 * 2;
		if (get(m1) > get(m2))
			r = m2;
		else
			l = m1;
	}
	for (; l <= min(r, pzs); ++l)
		chkmax(ans, get(l));
	cout << ans;
	return 0;
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
vector<ll> cnt;
vector<pair<ll, ll> > e;
vector<pair<ll, ll> > ppl;

ll get(ll pzsa) {
	ll pcsa = pzsa * S, res = 0, last = 0;
	int it = -1;
	//cout << pcsa << endl;
	//cout << e.size();
	while (pcsa > 0) {
		//cout << "LEL" << endl;
		//cout << pcsa << ' ' << pcsa << endl;
		it++;
		last = max(0ll, cnt[e[it].s] - pcsa);
		res += min(pcsa, cnt[e[it].s]) * ppl[e[it].s].f;
		pcsa -= min(pcsa, cnt[e[it].s]);
	}
	if (it < e.size())
		res += last * ppl[e[it].s].s;
	for (int i = it + 1; i < e.size(); ++i)
		res += cnt[e[i].s] * ppl[e[i].s].s;
	return res;
}

int main() {
	ios_base::sync_with_stdio(false);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	ppl.resize(n);
	cnt.resize(n);
	for (int i = 0; i < n; ++i) {
		int a, b;
		cin >> cnt[i] >> ppl[i].f >> ppl[i].s;
		sum += cnt[i];
		e.pb({ppl[i].s - ppl[i].f, i});
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S > sum) {
		e.pb({0, n});
		cnt.pb(pzs * S - sum);
		ppl.pb({0, 0});
	}
	sort(e.begin(), e.end());
	//get(1);
	ll l = 0, r = pzs;
	while (r - l > 2) {
		ll m1 = l + (r - l) / 3, m2 = l + (r - l) / 3 * 2;
		if (get(m1) < get(m2))
			l = m1;
		else
			r = m2;
	}
	ll ans = 0;
	for (; l <= r; ++l)
		chkmax(ans, get(l));
	cout << ans;
	return 0;
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
map<pair<ll, ll>, ll> d;
vector<pair<ll, ll> > ar;

ll get(ll a) {
	int it = 0;
	ll sum = 0, pcsa = S * a, last = 0;
	while (pcsa && it < ar.size()) {
		//cout << it << ' ' << pcsa << endl;
		if (pcsa > d[ar[it]]) {
			sum += ar[it].f * d[ar[it]];
			pcsa -= d[ar[it++]];
		}
		else {
			last = d[ar[it]] - pcsa;
			sum += ar[it].f * pcsa;
			pcsa = 0;
		}
	}
	if (it < ar.size())
		sum += ar[it].s * last;
	for (int i = it + 1; i < ar.size(); ++i)
		sum += ar[i].s * d[ar[i]];
	//cout << "Pizzas: " << a << ' ' << sum << endl;
	return sum;
}

bool cmp(pair<int, int> a, pair<int, int> b) {
	if (a.s - a.f == b.s - b.f)
		return a.f > b.f;
	return a.s - a.f < b.s - b.f;
}

int main() {
	ios_base::sync_with_stdio(false);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	for (int i = 0; i < n; ++i) {
		int s;
		pair<ll, ll> t;
		cin >> s >> t.f >> t.s;
		sum += s;
		d[t] += s;
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S - sum)
		d[{0, 0}] += pzs * S - sum;
	for (auto i : d) {
		ar.pb(i.f);
	}
	sort(ar.begin(), ar.end(), cmp);
	//get(0);
	//get(1);
	ll ans = 0;
	ll l = 0, r = pzs;
	while (l + 2 < r) {
		ll m1 = l + (r - l) / 3, m2 = l + (r - l) / 3 * 2;
		if (get(m1) > get(m2))
			r = m2;
		else
			l = m1;
	}
	for (; l <= min(r, pzs); ++l)
		chkmax(ans, get(l));
	cout << ans;
	return 0;
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
vector<ll> cnt;
vector<pair<int, int> > e;
vector<pair<int, int> > ppl;

ll get(ll pzsa) {
	ll pcsa = pzsa * S, res = 0;
	int it = -1, last = 0;
	//cout << pcsa << endl;
	//cout << e.size();
	while (pcsa > 0) {
		//cout << "LEL" << endl;
		//cout << pcsa << ' ' << pcsa << endl;
		it++;
		last = max(0ll, cnt[e[it].s] - pcsa);
		res += min(pcsa, cnt[e[it].s]) * ppl[e[it].s].f;
		pcsa -= min(pcsa, cnt[e[it].s]);
	}
	if (it < e.size())
		res += last * ppl[e[it].s].s;
	for (int i = it + 1; i < e.size(); ++i)
		res += cnt[e[i].s] * ppl[e[i].s].s;
	return res;
}

int main() {
	ios_base::sync_with_stdio(false);
	freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	ppl.resize(n);
	cnt.resize(n);
	for (int i = 0; i < n; ++i) {
		int a, b;
		cin >> cnt[i] >> ppl[i].f >> ppl[i].s;
		sum += cnt[i];
		e.pb({ppl[i].s - ppl[i].f, i});
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S > sum) {
		e.pb({0, n});
		cnt.pb(pzs * S - sum);
		ppl.pb({0, 0});
	}
	sort(e.begin(), e.end());
	//get(1);
	ll l = 0, r = pzs;
	while (r - l > 2) {
		ll m1 = l + (r - l) / 3, m2 = l + (r - l) / 3 * 2;
		if (get(m1) < get(m2))
			l = m1;
		else
			r = m2;
	}
	ll ans = 0;
	for (; l <= r; ++l)
		chkmax(ans, get(l));
	cout << ans;
	return 0;
}


#include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#include <list>
#include <time.h>
#include <math.h>
#include <random>
#include <deque>
#include <queue>
#include <cassert>
#include <unordered_map>
#include <iomanip>

using namespace std;

typedef long long ll;

mt19937 rnd(228);

int n, s;

const int N = 1e5 + 7;

int x[N], a[N], b[N];

ll need;

ll f(ll first)
{
    ll second = (need - first);
    first *= s;
    second *= s;
    vector <pair <int, int> > e;
    ll cur_sum = 0;
    ll sum_need = 0;
    for (int i = 0; i < n; i++)
    {
        sum_need += x[i];
        cur_sum += a[i] * (ll) x[i];
        e.push_back({b[i] - a[i], i});
    }
    ll left = sum_need - first, right = second;
    ll cur_have = 0;
    ll cur_grabbed = 0;
    ll ans = -1e18;
    sort(e.rbegin(), e.rend());
    for (auto c : e)
    {
        int i = c.second;
        ll can_max_push = min((ll) x[i], right - cur_have);
        if (cur_have + can_max_push >= left)
        {
            ans = max(ans, cur_sum + can_max_push * (b[i] - a[i]) + cur_grabbed);
        }
        ll can_min_push = max(0ll, min((ll) x[i], left - cur_have));
        if (cur_have + can_min_push >= left)
        {
            ans = max(ans, cur_sum + can_min_push * (b[i] - a[i]) + cur_grabbed);
        }
        cur_have += can_max_push;
        cur_grabbed += can_max_push * (b[i] - a[i]);
    }
    return ans;
}

int main()
{
#ifdef ONPC
    freopen("a.in", "r", stdin);
#endif
    scanf("%d%d", &n, &s);
    ll sum = 0;
    for (int i = 0; i < n; i++)
    {
        scanf("%d%d%d", &x[i], &a[i], &b[i]);
        sum += x[i];
    }
    need = (sum / s) + bool(sum % s);
    ll l = -1, r = need;
    while (l < r - 1)
    {
        ll m = (l + r) / 2;
        if (f(m) < f(m + 1))
        {
            l = m;
        }
        else
        {
            r = m;
        }
    }
    printf("%lld\n", f(l + 1));
}


#include<bits/stdc++.h>

#define f first
#define s second
#define mp make_pair
#define pb push_back
using namespace std;

template<typename T1, typename T2> chkmin(T1 & x, const T2 & y) {if (x > y) x = y;}
template<typename T1, typename T2> chkmax(T1 & x, const T2 & y) {if (x < y) x = y;}

typedef long long ll;
typedef long double ld;

ll S, pzs;
vector<ll> cnt;
vector<pair<int, int> > e;
vector<pair<int, int> > ppl;

ll get(ll pzsa) {
	ll pcsa = pzsa * S, res = 0;
	int it = -1, last = 0;
	//cout << pcsa << endl;
	//cout << e.size();
	while (pcsa > 0) {
		//cout << "LEL" << endl;
		//cout << pcsa << ' ' << pcsa << endl;
		it++;
		last = max(0ll, cnt[e[it].s] - pcsa);
		res += min(pcsa, cnt[e[it].s]) * ppl[e[it].s].f;
		pcsa -= min(pcsa, cnt[e[it].s]);
	}
	if (it < e.size())
		res += last * ppl[e[it].s].s;
	for (int i = it + 1; i < e.size(); ++i)
		res += cnt[e[i].s] * ppl[e[i].s].s;
	return res;
}

int main() {
	ios_base::sync_with_stdio(false);
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	cin >> n >> S;
	ll sum = 0;
	ppl.resize(n);
	cnt.resize(n);
	for (int i = 0; i < n; ++i) {
		int a, b;
		cin >> cnt[i] >> ppl[i].f >> ppl[i].s;
		sum += cnt[i];
		e.pb({ppl[i].s - ppl[i].f, i});
	}
	pzs = (sum + S - 1) / S;
	if (pzs * S > sum) {
		e.pb({0, n});
		cnt.pb(pzs * S - sum);
		ppl.pb({0, 0});
	}
	sort(e.begin(), e.end());
	//get(1);
	ll l = 0, r = pzs;
	while (r - l > 2) {
		ll m1 = l + (r - l) / 3, m2 = l + (r - l) / 3 * 2;
		if (get(m1) < get(m2))
			l = m1;
		else
			r = m2;
	}
	ll ans = 0;
	for (; l <= r; ++l)
		chkmax(ans, get(l));
	cout << ans;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007
#define ll long long int
#define ld long double
#define pb push_back
#define mkp make_pair
#define pii pair<int, int>
#define pll pair<long long int, long long int>
#define sci(x) scanf("%d", &x)
#define scl(x) scanf("%lld", &x)
#define fi first
#define sc second
#define deb 0

multiset<pll > pq;
ll A[100001], B[100001], T1[100001], T2[100001];
ll n;

ll get(ll x, ll y)
{
	for (ll i = 0; i < n; ++i) pq.insert(mkp(T1[i]-T2[i], i)), B[i] = A[i];
	pii tmp;
	ll ans = 0, a, b, i, j, p, q;
	while (!pq.empty() && x > 0 && y > 0) {
		tmp = *(--pq.end());
		a = tmp.fi;
		i = tmp.sc;
		tmp = *(pq.begin());
		b = tmp.fi;
		j = tmp.sc;
		if (a >= -b) {
			p = min(B[i], x);
			B[i] -= p;
			x -= p;
			ans += (p * T1[i]);
			if (B[i] == 0) {
				pq.erase(--pq.end());
			}
		} else {
			p = min(B[j], y);
			B[j] -= p;
			y -= p;
			ans += (p * T2[j]);
			if (B[j] == 0) {
				pq.erase(pq.begin());
			}
		}
	}
	while (!pq.empty() && x > 0) {
		tmp = *(--pq.end());
		a = tmp.fi;
		i = tmp.sc;
		p = min(B[i], x);
		B[i] -= p;
		x -= p;
		ans += (p * T1[i]);
		if (B[i] == 0) {
			pq.erase(--pq.end());
		}
	}
	while (!pq.empty() && y > 0) {
		tmp = *pq.begin();
		b = tmp.fi;
		j = tmp.sc;
		p = min(B[j], y);
		B[j] -= p;
		y -= p;
		ans += (p * T2[j]);
		if (B[j] == 0) {
			pq.erase(pq.begin());
		}
	}

	return ans;
}

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

	ll s, i, j, k, x, y, z, ans, start, mid, end;
	cin >> n >> s;
	x = 0;
	for (i = 0; i < n; ++i) cin >> A[i] >> T1[i] >> T2[i], x += A[i];
	x = (x + s - 1) / s;
	start = 0;
	end = x;

	while (end-start+1 >= 3) {
		mid = (start + end) >> 1;
		ll a = get((mid-1) * s, (x - mid + 1) * s);
		ll b = get(mid * s, (x - mid) * s);
		ll c = get((mid+1) % s, (x - mid - 1) * s);
		if (a <= b && b <= c) {
			start = mid + 1;
		} else if (a >= b && b >= c) {
			end = mid - 1;
		} else if (a <= b && b >= c) {
			cout << b << endl;
			return 0;
		}
	}

	y = 0;
	for (i = start; i <= end; ++i) {
		y = max(y, get(i*s, (x-i)*s));
	}
	cout << y << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007
#define ll long long int
#define ld long double
#define pb push_back
#define mkp make_pair
#define pii pair<int, int>
#define pll pair<long long int, long long int>
#define sci(x) scanf("%d", &x)
#define scl(x) scanf("%lld", &x)
#define fi first
#define sc second
#define deb 0

multiset<pll > pq;
ll A[100001], B[100001], T1[100001], T2[100001];
ll n;

ll get(ll x, ll y)
{
	for (ll i = 0; i < n; ++i) pq.insert(mkp(T1[i]-T2[i], i)), B[i] = A[i];
	pii tmp;
	ll ans = 0, a, b, i, j, p, q;
	while (!pq.empty() && x > 0 && y > 0) {
		tmp = *(--pq.end());
		a = tmp.fi;
		i = tmp.sc;
		tmp = *(pq.begin());
		b = tmp.fi;
		j = tmp.sc;
		if (a >= -b) {
			p = min(B[i], x);
			B[i] -= p;
			x -= p;
			ans += (p * T1[i]);
			if (B[i] == 0) {
				pq.erase(--pq.end());
			}
		} else {
			p = min(B[j], y);
			B[j] -= p;
			y -= p;
			ans += (p * T2[j]);
			if (B[j] == 0) {
				pq.erase(pq.begin());
			}
		}
	}
	while (!pq.empty() && x > 0) {
		tmp = *(--pq.end());
		a = tmp.fi;
		i = tmp.sc;
		p = min(B[i], x);
		B[i] -= p;
		x -= p;
		ans += (p * T1[i]);
		if (B[i] == 0) {
			pq.erase(--pq.end());
		}
	}
	while (!pq.empty() && y > 0) {
		tmp = *pq.begin();
		b = tmp.fi;
		j = tmp.sc;
		p = min(B[j], y);
		B[j] -= p;
		y -= p;
		ans += (p * T2[j]);
		if (B[j] == 0) {
			pq.erase(pq.begin());
		}
	}

	return ans;
}

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

	ll s, i, j, k, x, y, z, ans, start, mid, end;
	cin >> n >> s;
	x = 0;
	for (i = 0; i < n; ++i) cin >> A[i] >> T1[i] >> T2[i], x += A[i];
	x = (x + s - 1) / s;
	start = 0;
	end = x;

	while (end-start+1 >= 3) {
		mid = (start + end) >> 1;
		ll a = get((mid-1) * s, (x - mid + 1) * s);
		ll b = get(mid * s, (x - mid) * s);
		ll c = get((mid+1) * s, (x - mid - 1) * s);
		if (a <= b && b <= c) {
			start = mid + 1;
		} else if (a >= b && b >= c) {
			end = mid - 1;
		} else if (a <= b && b >= c) {
			cout << b << endl;
			return 0;
		}
	}

	y = 0;
	for (i = start; i <= end; ++i) {
		y = max(y, get(i*s, (x-i)*s));
	}
	cout << y << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007
#define ll long long int
#define ld long double
#define pb push_back
#define mkp make_pair
#define pii pair<int, int>
#define pll pair<long long int, long long int>
#define sci(x) scanf("%d", &x)
#define scl(x) scanf("%lld", &x)
#define fi first
#define sc second
#define deb 0

multiset<pll > pq;
pll tmp[100001];
ll A[100001], B[100001], T1[100001], T2[100001];
ll n;

ll get(ll x, ll y)
{
	ll ans = 0, a, b, i, j, k, p, q;
	for (i = 0; i < n; ++i) tmp[i] = mkp(T1[i]-T2[i], i), B[i] = A[i];
	sort(tmp, tmp+n);
	i = 0; j = n-1;
	while (i <= j && x > 0 && y > 0) {
		if (tmp[j].fi >= -tmp[i].fi) {
			q = tmp[j].sc;
			p = min(x, B[q]);
			B[q] -= p;
			x -= p;
			ans += (p * T1[q]);
			if (B[q] == 0) j--;
		} else {
			q = tmp[i].sc;
			p = min(y, B[q]);
			B[q] -= p;
			y -= p;
			ans += (p * T2[q]);
			if (B[q] == 0) i++;
		}
	}
	while (i <= j && x > 0) {
		q = tmp[j].sc;
		p = min(x, B[q]);
		B[q] -= p;
		x -= p;
		ans += (p * T1[q]);
		if (B[q] == 0) j--;
	}
	while (i <= j && y > 0) {
		q = tmp[i].sc;
		p = min(y, B[q]);
		B[q] -= p;
		y -= p;
		ans += (p * T2[q]);
		if (B[q] == 0) i++;
	}
	return ans;
}

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

	ll s, i, j, k, x, y, z, ans, start, mid, end;
	cin >> n >> s;
	x = 0;
	for (i = 0; i < n; ++i) cin >> A[i] >> T1[i] >> T2[i], x += A[i];
	x = (x + s - 1) / s;
	start = 0;
	end = x;

	while (end-start+1 >= 3) {
		mid = (start + end) >> 1;
		ll a = get((mid-1) * s, (x - mid + 1) * s);
		ll b = get(mid * s, (x - mid) * s);
		ll c = get((mid+1) * s, (x - mid - 1) * s);
		if (a <= b && b <= c) {
			start = mid + 1;
		} else if (a >= b && b >= c) {
			end = mid - 1;
		} else if (a <= b && b >= c) {
			cout << b << endl;
			return 0;
		}
	}

	y = 0;
	for (i = start; i <= end; ++i) {
		y = max(y, get(i*s, (x-i)*s));
	}
	cout << y << endl;

	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
struct rec
{
	long long num,dif;
};
int i,j,m,n,maxi,maxpos;
long long t,sum,tot,ans;
int s[100005],a[100005],b[100005],d[100005];
rec num[100005];
long long divup(long long a,long long b){
	if ((a%b)==0) return a/b;
	else return a/b+1;
}
bool cmp(rec a,rec b){
	if (a.dif>b.dif)return true;
	else return false;
}
int main(){
	scanf("%d%lld",&n,&t);
	ans=sum=0;
	maxi=0;
	for(i=1;i<=n;i++){
		scanf("%d%d%d",&s[i],&a[i],&b[i]);
		if (b[i]>maxi) {
			maxi=b[i];
			maxpos=i;
		}
		//d[i]=a[i]-b[i];
		num[i].num=s[i];
		num[i].dif=a[i]-b[i];//choose the second type first;
		sum+=s[i];
		ans+=s[i]*b[i];
	}
	long long temp;
	long long less;
	tot=divup(sum,t);
	less=t-(tot*t-sum);
	/*s[maxpos]+=temp;
	num[maxpos].num+=temp;
	ans+=temp*maxi;*/
	sort(num+1,num+n+1,cmp);
	temp=0;
	i=1;
	//bool flag=false;
	long long addd=0;
	while(i<=n){
		while(temp<t){
			while ((num[i].num==0)&&(i<=n))i++;
			if (i>n){
				break;
			}else{
				if (num[i].dif<0){
					t=max(temp,less);
					//flag=true;
				}
				if (num[i].num>=t-temp){
					num[i].num-=(t-temp);
					addd+=(t-temp)*num[i].dif;
					temp=t;
				}else{
					//num[i].num=0;
					addd+=num[i].num*num[i].dif;
					temp+=num[i].num;
					num[i].num=0;
				}
			}
		}
		if (addd>0) ans+=addd;
		else break;
		addd=0;
		temp=0;
	}
	//printf("%d\n",i);
	printf("%lld\n",ans);
	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
struct rec
{
	long long num,dif;
};
int i,j,m,n,maxi,maxpos;
long long t,sum,tot,ans;
long long s[100005],a[100005],b[100005],d[100005];
rec num[100005];
long long divup(long long a,long long b){
	if ((a%b)==0) return a/b;
	else return a/b+1;
}
bool cmp(rec a,rec b){
	if (a.dif>b.dif)return true;
	else return false;
}
int main(){
	scanf("%d%lld",&n,&t);
	ans=sum=0;
	maxi=0;
	for(i=1;i<=n;i++){
		scanf("%lld%lld%lld",&s[i],&a[i],&b[i]);
		if (b[i]>maxi) {
			maxi=b[i];
			maxpos=i;
		}
		//d[i]=a[i]-b[i];
		num[i].num=s[i];
		num[i].dif=a[i]-b[i];//choose the second type first;
		sum+=s[i];
		ans+=s[i]*b[i];
	}
	long long temp;
	long long less;
	tot=divup(sum,t);
	less=t-(tot*t-sum);
	/*s[maxpos]+=temp;
	num[maxpos].num+=temp;
	ans+=temp*maxi;*/
	sort(num+1,num+n+1,cmp);
	temp=0;
	i=1;
	//bool flag=false;
	long long addd=0;
	long long k;
	while(i<=n){
		while(temp<t){
			while ((num[i].num==0)&&(i<=n))i++;
			if (i>n){
				break;
			}else{
				if (num[i].dif<0){
					t=max(temp,less);
					//flag=true;
				}
				if (num[i].num>=t-temp){
					if (temp==0){
						if (num[i].dif<0){
							i=n;
							break;
						}
						k=num[i].num/t;
						addd+=k*t*num[i].dif;
						temp=t;
					}else{
						num[i].num-=(t-temp);
						addd+=(t-temp)*num[i].dif;
						temp=t;
					}
				}else{
					//num[i].num=0;
					addd+=num[i].num*num[i].dif;
					temp+=num[i].num;
					num[i].num=0;
				}
			}
		}
		if (addd>0) ans+=addd;
		else break;
		addd=0;
		temp=0;
	}
	//printf("%d\n",less);
	/*for(i=1;i<=n;i++){
		printf("%d %d\n",num[i].num,num[i].dif);
	}*/
	printf("%lld\n",ans);
	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
struct rec
{
	long long num,dif;
};
int i,j,m,n,maxi,maxpos;
long long t,sum,tot,ans;
int s[100005],a[100005],b[100005],d[100005];
rec num[100005];
long long divup(long long a,long long b){
	if ((a%b)==0) return a/b;
	else return a/b+1;
}
bool cmp(rec a,rec b){
	if (a.dif>b.dif)return true;
	else return false;
}
int main(){
	scanf("%d%lld",&n,&t);
	ans=sum=0;
	maxi=0;
	for(i=1;i<=n;i++){
		scanf("%d%d%d",&s[i],&a[i],&b[i]);
		if (b[i]>maxi) {
			maxi=b[i];
			maxpos=i;
		}
		//d[i]=a[i]-b[i];
		num[i].num=s[i];
		num[i].dif=a[i]-b[i];//choose the second type first;
		sum+=s[i];
		ans+=s[i]*b[i];
	}
	long long temp;
	/*tot=divup(sum,t);
	temp=(tot*t-sum);
	s[maxpos]+=temp;
	num[maxpos].num+=temp;
	ans+=temp*maxi;*/
	sort(num+1,num+n+1,cmp);
	temp=0;
	i=1;
	long long addd=0;
	while(i<=n){
		while(temp<t){
			while ((num[i].num==0)&&(i<=n))i++;
			if (i>n){
				break;
			}else{
				if (num[i].num>=t-temp){
					num[i].num-=(t-temp);
					addd+=(t-temp)*num[i].dif;
					temp=t;
				}else{
					//num[i].num=0;
					addd+=num[i].num*num[i].dif;
					temp+=num[i].num;
					num[i].num=0;
				}
			}
		}
		if (addd>0) ans+=addd;
		else break;
		addd=0;
		temp=0;
	}
	printf("%lld\n",ans);
	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
struct rec
{
	long long num,dif;
};
int i,j,m,n,maxi,maxpos;
long long t,sum,tot,ans;
long long s[100005],a[100005],b[100005],d[100005];
rec num[100005];
long long divup(long long a,long long b){
	if ((a%b)==0) return a/b;
	else return a/b+1;
}
bool cmp(rec a,rec b){
	if (a.dif>b.dif)return true;
	else return false;
}
int main(){
	scanf("%d%lld",&n,&t);
	ans=sum=0;
	maxi=0;
	for(i=1;i<=n;i++){
		scanf("%lld%lld%lld",&s[i],&a[i],&b[i]);
		if (b[i]>maxi) {
			maxi=b[i];
			maxpos=i;
		}
		//d[i]=a[i]-b[i];
		num[i].num=s[i];
		num[i].dif=a[i]-b[i];//choose the second type first;
		sum+=s[i];
		ans+=s[i]*b[i];
	}
	long long temp;
	long long less;
	tot=divup(sum,t);
	less=t-(tot*t-sum);
	/*s[maxpos]+=temp;
	num[maxpos].num+=temp;
	ans+=temp*maxi;*/
	sort(num+1,num+n+1,cmp);
	temp=0;
	i=1;
	//bool flag=false;
	long long addd=0;
	long long k;
	while(i<=n){
		while(temp<t){
			while ((num[i].num==0)&&(i<=n))i++;
			if (i>n){
				break;
			}else{
				if (num[i].dif<0){
					t=max(temp,less);
					//flag=true;
				}
				if (num[i].num>=t-temp){
					if (temp==0){
						if (num[i].dif<0){
							i=n;
							break;
						}
						k=num[i].num/t;
						addd+=k*t*num[i].dif;
						num[i].num-=k*t;
						temp=t;
					}else{
						num[i].num-=(t-temp);
						addd+=(t-temp)*num[i].dif;
						temp=t;
					}
				}else{
					//num[i].num=0;
					addd+=num[i].num*num[i].dif;
					temp+=num[i].num;
					num[i].num=0;
				}
			}
		}
		if (addd>0) ans+=addd;
		else break;
		addd=0;
		temp=0;
	}
	//printf("%d\n",less);
	/*for(i=1;i<=n;i++){
		printf("%d %d\n",num[i].num,num[i].dif);
	}*/
	printf("%lld\n",ans);
	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
struct rec
{
	long long num,dif;
};
int i,j,m,n,maxi,maxpos;
long long t,sum,tot,ans;
int s[100005],a[100005],b[100005],d[100005];
rec num[100005];
long long divup(long long a,long long b){
	if ((a%b)==0) return a/b;
	else return a/b+1;
}
bool cmp(rec a,rec b){
	if (a.dif>b.dif)return true;
	else return false;
}
int main(){
	scanf("%d%lld",&n,&t);
	ans=sum=0;
	maxi=0;
	for(i=1;i<=n;i++){
		scanf("%d%d%d",&s[i],&a[i],&b[i]);
		if (b[i]>maxi) {
			maxi=b[i];
			maxpos=i;
		}
		//d[i]=a[i]-b[i];
		num[i].num=s[i];
		num[i].dif=a[i]-b[i];//choose the second type first;
		sum+=s[i];
		ans+=s[i]*b[i];
	}
	long long temp;
	long long less;
	tot=divup(sum,t);
	less=t-(tot*t-sum);
	/*s[maxpos]+=temp;
	num[maxpos].num+=temp;
	ans+=temp*maxi;*/
	sort(num+1,num+n+1,cmp);
	temp=0;
	i=1;
	//bool flag=false;
	long long addd=0;
	while(i<=n){
		while(temp<t){
			while ((num[i].num==0)&&(i<=n))i++;
			if (i>n){
				break;
			}else{
				if (num[i].dif<0){
					t=max(temp,less);
					//flag=true;
				}
				if (num[i].num>=t-temp){
					num[i].num-=(t-temp);
					addd+=(t-temp)*num[i].dif;
					temp=t;
				}else{
					//num[i].num=0;
					addd+=num[i].num*num[i].dif;
					temp+=num[i].num;
					num[i].num=0;
				}
			}
		}
		if (addd>0) ans+=addd;
		else break;
		addd=0;
		temp=0;
	}
	//printf("%d\n",less);
	/*for(i=1;i<=n;i++){
		printf("%d %d\n",num[i].num,num[i].dif);
	}*/
	printf("%lld\n",ans);
	return 0;
}


#include <cstdio>
#include <algorithm>
using namespace std;
struct rec
{
	long long num,dif;
};
int i,j,m,n,maxi,maxpos;
long long t,sum,tot,ans;
long long s[100005],a[100005],b[100005],d[100005];
rec num[100005];
long long divup(long long a,long long b){
	if ((a%b)==0) return a/b;
	else return a/b+1;
}
bool cmp(rec a,rec b){
	if (a.dif>b.dif)return true;
	else return false;
}
int main(){
	scanf("%d%lld",&n,&t);
	ans=sum=0;
	maxi=0;
	for(i=1;i<=n;i++){
		scanf("%lld%lld%lld",&s[i],&a[i],&b[i]);
		if (b[i]>maxi) {
			maxi=b[i];
			maxpos=i;
		}
		//d[i]=a[i]-b[i];
		num[i].num=s[i];
		num[i].dif=a[i]-b[i];//choose the second type first;
		sum+=s[i];
		ans+=s[i]*b[i];
	}
	long long temp;
	long long less;
	tot=divup(sum,t);
	less=t-(tot*t-sum);
	/*s[maxpos]+=temp;
	num[maxpos].num+=temp;
	ans+=temp*maxi;*/
	sort(num+1,num+n+1,cmp);
	temp=0;
	i=1;
	//bool flag=false;
	long long addd=0;
	while(i<=n){
		while(temp<t){
			while ((num[i].num==0)&&(i<=n))i++;
			if (i>n){
				break;
			}else{
				if (num[i].dif<0){
					t=max(temp,less);
					//flag=true;
				}
				if (num[i].num>=t-temp){
					num[i].num-=(t-temp);
					addd+=(t-temp)*num[i].dif;
					temp=t;
				}else{
					//num[i].num=0;
					addd+=num[i].num*num[i].dif;
					temp+=num[i].num;
					num[i].num=0;
				}
			}
		}
		if (addd>0) ans+=addd;
		else break;
		addd=0;
		temp=0;
	}
	//printf("%d\n",less);
	/*for(i=1;i<=n;i++){
		printf("%d %d\n",num[i].num,num[i].dif);
	}*/
	printf("%lld\n",ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100500;
ll a[N],b[N],sl[N],ha[N],hb[N];
vector<pair<pair<ll,ll>,ll> > v;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,i;
    ll s,ss=0,sum=0;
    cin>>n>>s;
    for(i=0;i<n;i++){
        cin>>sl[i]>>a[i]>>b[i];
        v.push_back({{a[i]-b[i],b[i]},sl[i]});
    }
    sort(v.begin(),v.end());
    reverse(v.begin(),v.end());
    for(i=0;i<n;i++){
        a[i+1] = v[i].first.first+v[i].first.second;
        b[i+1] = v[i].first.second;
        sl[i+1] = v[i].second;
        ss+=sl[i+1];
        ha[i+1] = ha[i]+a[i+1]*sl[i+1];
       // cout<<ha[i+1]<<" ";
    }
   // cout<<endl;
    for(i=n;i>0;i--){
        hb[i] = hb[i+1]+b[i]*sl[i];
       // cout<<hb[i]<<" ";
    }
   // cout<<endl;
    ll tot = (ss+s-1)/s,ans=hb[1];
   // cout<<ans<<" "<<tot<<endl;
    for(i=1;i<=n;i++){
        sum+=sl[i];
        if((sum+s-1)/s + (ss-sum+s-1)/s <= tot){
            ans=max(ans,ha[i]+hb[i+1]);
            //cout<<"why"<<endl;
        }
        if(sum%s <=sl[i]){
            ll x= sl[i] - (sum%s),y=sum%s;
           // cout<<i<<" "<<ha[i-1]+hb[i+1]+x*a[i]+y*b[i]<<endl;
            ans=max(ans,ha[i-1]+hb[i+1]+x*a[i]+y*b[i]);
        }
    }
    cout<<ans;
}
/*
5 1
2 7 5
2 4 3
2 6 7
2 3 8
2 4 7
*/


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100500;
ll a[N],b[N],sl[N],ha[N],hb[N];
vector<pair<pair<ll,ll>,ll> > v;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,i;
    ll s,ss=0,sum=0;
    cin>>n>>s;
    for(i=0;i<n;i++){
        cin>>sl[i]>>a[i]>>b[i];
        v.push_back({{a[i]-b[i],b[i]},sl[i]});
    }
    sort(v.begin(),v.end());
    reverse(v.begin(),v.end());
    for(i=0;i<n;i++){
        a[i+1] = v[i].first.first+v[i].first.second;
        b[i+1] = v[i].first.second;
        sl[i+1] = v[i].second;
        ss+=sl[i+1];
        ha[i+1] = ha[i]+a[i+1]*sl[i+1];
       // cout<<ha[i+1]<<" ";
    }
   // cout<<endl;
    for(i=n;i>0;i--){
        hb[i] = hb[i+1]+b[i]*sl[i];
       // cout<<hb[i]<<" ";
    }
   // cout<<endl;
    ll tot = (ss+s-1)/s,ans=hb[1];
   // cout<<ans<<" "<<tot<<endl;
    for(i=1;i<=n;i++){
        sum+=sl[i];
        if((sum+s-1)/s + (ss-sum+s-1)/s <= tot){
            ans=max(ans,ha[i]+hb[i+1]);
            //cout<<"why"<<endl;
        }
        if(sum%s <=sl[i]){
            ll x,y;
            x= sl[i] - (sum%s),y=sum%s;
           // cout<<i<<" "<<ha[i-1]+hb[i+1]+x*a[i]+y*b[i]<<endl;
            ans=max(ans,ha[i-1]+hb[i+1]+x*a[i]+y*b[i]);
        }
        if((ss-sum+sl[i])%s <=sl[i]){
             ll x=(ss-sum+sl[i])%s,y=sl[i]-x;
             ans=max(ans,ha[i-1]+hb[i+1]+x*a[i]+y*b[i]);
        }
    }
    cout<<ans;
}
/*
5 1
2 7 5
2 4 3
2 6 7
2 3 8
2 4 7
*/


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100500;
ll a[N],b[N],sl[N],ha[N],hb[N];
vector<pair<pair<ll,ll>,ll> > v;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,i;
    ll s,ss=0,sum=0;
    cin>>n>>s;
    for(i=0;i<n;i++){
        cin>>sl[i]>>a[i]>>b[i];
        v.push_back({{a[i]-b[i],b[i]},sl[i]});
    }
    sort(v.begin(),v.end());
    reverse(v.begin(),v.end());
    for(i=0;i<n;i++){
        a[i+1] = v[i].first.first+v[i].first.second;
        b[i+1] = v[i].first.second;
        sl[i+1] = v[i].second;
        ss+=sl[i+1];
        ha[i+1] = ha[i]+a[i+1]*sl[i+1];
       // cout<<ha[i+1]<<" ";
    }
   // cout<<endl;
    for(i=n;i>0;i--){
        hb[i] = hb[i+1]+b[i]*sl[i];
       // cout<<hb[i]<<" ";
    }
   // cout<<endl;
    ll tot = (ss+s-1)/s,ans=hb[1];
   // cout<<ans<<" "<<tot<<endl;
    for(i=1;i<=n;i++){
        sum+=sl[i];
        if((sum+s-1)/s + (ss-sum+s-1)/s <= tot){
            ans=max(ans,ha[i]+hb[i+1]);
            //cout<<"why"<<endl;
        }
        if(sum%s <=sl[i]){
            ll x,y;
            x= sl[i] - (sum%s),y=sum%s;
           // cout<<i<<" "<<ha[i-1]+hb[i+1]+x*a[i]+y*b[i]<<endl;
            ans=max(ans,ha[i-1]+hb[i+1]+x*a[i]+y*b[i]);
        }
        if(s-((sum-sl[i])%s) <=sl[i]){
             ll x=s-((sum-sl[i])%s),y=sl[i]-x;
             ans=max(ans,ha[i-1]+hb[i+1]+x*a[i]+y*b[i]);
        }
    }
    cout<<ans;
}
/*
5 1
2 7 5
2 4 3
2 6 7
2 3 8
2 4 7
*/


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100500;
ll a[N],b[N],sl[N],ha[N],hb[N];
vector<pair<pair<ll,ll>,ll> > v;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,i;
    ll s,ss=0,sum=0;
    cin>>n>>s;
    for(i=0;i<n;i++){
        cin>>sl[i]>>a[i]>>b[i];
        v.push_back({{a[i],b[i]},sl[i]});
    }
    sort(v.begin(),v.end());
    reverse(v.begin(),v.end());
    for(i=0;i<n;i++){
        a[i+1] = v[i].first.first;
        b[i+1] = v[i].first.second;
        sl[i+1] = v[i].second;
        ss+=sl[i+1];
        ha[i+1] = ha[i]+a[i+1]*sl[i+1];
    }
    for(i=n;i>0;i--){
        hb[i] = hb[i+1]+b[i]*sl[i];
    }
    ll tot = (ss+s-1)/s,ans=hb[1];
    for(i=1;i<=n;i++){
        sum+=sl[i];
        if((sum+s-1)/s + (ss-sum+s-1)/s <= tot){
            ans=max(ans,ha[i]+hb[i+1]);
        }
        if(sum%s <=sl[i]){
            ll x= sl[i] - (sum%s),y=sum%s;
            ans=max(ans,ha[i-1]+hb[i+1]+x*a[i]+y*b[i]);
        }
    }
    cout<<ans;
}


//============================================================================
// Name        : asd.cpp
// Author      : bestard
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <bits/stdc++.h>
#define maxn 100005

using namespace std;
typedef long long ll;
typedef pair<int, int> par;

struct r{
    ll c, a, b;
}A[100005];

ll B[100005];
ll D[100005];

bool comp( const r s1, const r s2 ){
    return s1.a - s1.b > s2.a - s2.b;
}

bool comp1( const r s1, const r s2 ){
    return abs( s1.a - s1.b ) < abs(s2.a - s2.b);
}

int main() {
    #ifdef acm
        freopen("a.in", "r", stdin);
    #endif // acm
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n;
    ll S;

    cin >> n >> S;

    ll s = 0;
    for( int i = 1; i <= n; i ++ ){
        cin >> A[i].c >> A[i].a >> A[i].b;
        s += min( A[i].a, A[i].b )*A[i].c;
    }

    sort( A+1, A+1+n, comp1 );

    ll mej = 0, ca = 0, cb = 0, ig = 0;
    for( int i = 1; i <= n ; i ++ ){
        B[i] = B[i-1]+A[i].c, D[i] = A[i].a - A[i].b;
        mej += abs( D[i] )*A[i].c;

        if( A[i].a >= A[i].b ) ca += A[i].c;
        else  cb += A[i].c;
    }

    cb %= S, ca %= S;

    if( ca + cb > S ){
        cout << s+mej << '\n';
        return 0;
    }
//65
    ll tmp = 0;
    ll a = 0, b = 0;
    for( int i = 1; i <= n ; i ++ ){
        if( A[i].a >= A[i].b ){
            if( ca == 0 ) continue;

            if( ca > A[i].c ){
                ca -= A[i].c;
                a += (A[i].a-A[i].b) * A[i].c;
            }else{
                a += (A[i].a-A[i].b) * ca;
                ca = 0;
            }
        }else
        if( A[i].a < A[i].b ){
            if( cb == 0 ) continue;

            if( cb > A[i].c ){
                cb -= A[i].c;
                b += (A[i].b-A[i].a) * A[i].c;
            }else{
                b += (A[i].b-A[i].a) * cb;
                cb = 0;
            }
        }

    }

    ll smej = s + mej - min( a, b );

    cout << smej << '\n';
    return 0;

    /*mej = 0, ca = 0, cb = 0, ig = 0;
    for( int i = 1; i <= n ; i ++ ){
        B[i] = B[i-1]+A[i].c, D[i] = A[i].a - A[i].b;
        mej += abs( D[i] )*A[i].c;

        if( A[i].a > A[i].b ) ca += A[i].c;
        else  cb += A[i].c;
    }

    cb %= S, ca %= S;

    tmp = 0;
    for( int i = 1; i <= n ; i ++ ){
        if( A[i].a > A[i].b ){
            if( ca == 0 ) continue;

            if( ca > A[i].c ){
                ca -= A[i].c;
                mej -= (A[i].a-A[i].b) * A[i].c;
            }else{
                ca = 0;
                mej -= (A[i].a-A[i].b) * ca;
            }
        }else
        if( A[i].a < A[i].b ){
            if( cb == 0 ) continue;

            if( cb > A[i].c ){
                cb -= A[i].c;
                mej -= (A[i].b-A[i].a) * A[i].c;
            }else{
                cb = 0;
                mej -= (A[i].b-A[i].b) * cb;
            }
        }

    }*/

    cout << s + mej << '\n';

    return 0;
}


//============================================================================
// Name        : asd.cpp
// Author      : bestard
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <bits/stdc++.h>
#define maxn 100005

using namespace std;
typedef long long ll;
typedef pair<int, int> par;

struct r{
    ll c, a, b;
}A[100005];

ll B[100005];
ll D[100005];

bool comp( const r s1, const r s2 ){
    return s1.a - s1.b > s2.a - s2.b;
}

bool comp1( const r s1, const r s2 ){
    return abs( s1.a - s1.b ) < abs(s2.a - s2.b);
}

int main() {
    #ifdef acm
        freopen("a.in", "r", stdin);
    #endif // acm
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n;
    ll S;

    cin >> n >> S;

    ll s = 0;
    for( int i = 1; i <= n; i ++ ){
        cin >> A[i].c >> A[i].a >> A[i].b;
        s += min( A[i].a, A[i].b )*A[i].c;
    }

    sort( A+1, A+1+n, comp1 );

    ll mej = 0, ca = 0, cb = 0, ig = 0;
    for( int i = 1; i <= n ; i ++ ){
        B[i] = B[i-1]+A[i].c, D[i] = A[i].a - A[i].b;
        mej += abs( D[i] )*A[i].c;

        if( A[i].a >= A[i].b ) ca += A[i].c;
        else  cb += A[i].c;
    }

    cb %= S, ca %= S;

    if( ca + cb > S ){
        cout << s+mej << '\n';
        return 0;
    }

    ll tmp = 0;
    ll a = 0, b = 0;
    for( int i = 1; i <= n ; i ++ ){
        if( A[i].a >= A[i].b ){
            if( ca == 0 ) continue;

            if( ca > A[i].c ){
                ca -= A[i].c;
                a += (A[i].a-A[i].b) * A[i].c;
            }else{
                a += (A[i].a-A[i].b) * ca;
                ca = 0;
            }
        }else
        if( A[i].a < A[i].b ){
            if( cb == 0 ) continue;

            if( cb > A[i].c ){
                cb -= A[i].c;
                b += (A[i].b-A[i].a) * A[i].c;
            }else{
                b += (A[i].b-A[i].a) * cb;
                cb = 0;
            }
        }

    }

    ll smej = s + mej - min( a, b );

    cout << smej << '\n';
    return 0;

    /*mej = 0, ca = 0, cb = 0, ig = 0;
    for( int i = 1; i <= n ; i ++ ){
        B[i] = B[i-1]+A[i].c, D[i] = A[i].a - A[i].b;
        mej += abs( D[i] )*A[i].c;

        if( A[i].a > A[i].b ) ca += A[i].c;
        else  cb += A[i].c;
    }

    cb %= S, ca %= S;

    tmp = 0;
    for( int i = 1; i <= n ; i ++ ){
        if( A[i].a > A[i].b ){
            if( ca == 0 ) continue;

            if( ca > A[i].c ){
                ca -= A[i].c;
                mej -= (A[i].a-A[i].b) * A[i].c;
            }else{
                ca = 0;
                mej -= (A[i].a-A[i].b) * ca;
            }
        }else
        if( A[i].a < A[i].b ){
            if( cb == 0 ) continue;

            if( cb > A[i].c ){
                cb -= A[i].c;
                mej -= (A[i].b-A[i].a) * A[i].c;
            }else{
                cb = 0;
                mej -= (A[i].b-A[i].b) * cb;
            }
        }

    }*/

    cout << s + mej << '\n';

    return 0;
}


//============================================================================
// Name        : asd.cpp
// Author      : bestard
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <bits/stdc++.h>
#define maxn 100005

using namespace std;
typedef long long ll;
typedef pair<int, int> par;

struct r{
    ll c, a, b;
}A[100005];

ll B[100005];
ll D[100005];

bool comp( const r s1, const r s2 ){
    return s1.a - s1.b > s2.a - s2.b;
}

bool comp1( const r s1, const r s2 ){
    return abs( s1.a - s1.b ) < abs(s2.a - s2.b);
}

int main() {
    #ifdef acm
        freopen("a.in", "r", stdin);
    #endif // acm
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n;
    ll S;

    cin >> n >> S;

    ll s = 0;
    for( int i = 1; i <= n; i ++ ){
        cin >> A[i].c >> A[i].a >> A[i].b;
        s += min( A[i].a, A[i].b )*A[i].c;
    }

    sort( A+1, A+1+n, comp1 );

    ll mej = 0, ca = 0, cb = 0, ig = 0;
    for( int i = 1; i <= n ; i ++ ){
        B[i] = B[i-1]+A[i].c, D[i] = A[i].a - A[i].b;
        mej += abs( D[i] )*A[i].c;

        if( A[i].a >= A[i].b ) ca += A[i].c;
        else  cb += A[i].c;
    }

    cb %= S, ca %= S;

    ll tmp = 0;
    ll a = 0, b = 0;
    for( int i = 1; i <= n ; i ++ ){
        if( A[i].a >= A[i].b ){
            if( ca == 0 ) continue;

            if( ca > A[i].c ){
                ca -= A[i].c;
                a += (A[i].a-A[i].b) * A[i].c;
            }else{
                a += (A[i].a-A[i].b) * ca;
                ca = 0;
            }
        }else
        if( A[i].a < A[i].b ){
            if( cb == 0 ) continue;

            if( cb > A[i].c ){
                cb -= A[i].c;
                b += (A[i].b-A[i].a) * A[i].c;
            }else{
                b += (A[i].b-A[i].a) * cb;
                cb = 0;
            }
        }

    }

    ll smej = s + mej - min( a, b );

    cout << smej << '\n';
    return 0;

    /*mej = 0, ca = 0, cb = 0, ig = 0;
    for( int i = 1; i <= n ; i ++ ){
        B[i] = B[i-1]+A[i].c, D[i] = A[i].a - A[i].b;
        mej += abs( D[i] )*A[i].c;

        if( A[i].a > A[i].b ) ca += A[i].c;
        else  cb += A[i].c;
    }

    cb %= S, ca %= S;

    tmp = 0;
    for( int i = 1; i <= n ; i ++ ){
        if( A[i].a > A[i].b ){
            if( ca == 0 ) continue;

            if( ca > A[i].c ){
                ca -= A[i].c;
                mej -= (A[i].a-A[i].b) * A[i].c;
            }else{
                ca = 0;
                mej -= (A[i].a-A[i].b) * ca;
            }
        }else
        if( A[i].a < A[i].b ){
            if( cb == 0 ) continue;

            if( cb > A[i].c ){
                cb -= A[i].c;
                mej -= (A[i].b-A[i].a) * A[i].c;
            }else{
                cb = 0;
                mej -= (A[i].b-A[i].b) * cb;
            }
        }

    }*/

    cout << s + mej << '\n';

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define REPN(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a, _b = b; i <= _b; ++i)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define sz(a) (int)a.size()

typedef pair<int, int> pii;
typedef vector<int> vi;
typedef long long llong;

const int maxN = 100005;

struct contestant  { llong s, a, b;};
bool compByA(contestant x, contestant y) { return x.a > y.a; }
bool compByB(contestant x, contestant y) { return x.b > y.b; }

int N;
llong S, nPizza;
vector <contestant> A, B;

llong maxHappiness(llong typeA)
{
    llong aSlices = 1L * typeA * S, bSlices = 1LL * (nPizza - typeA) * S,
            sumHappiness = 0;
    vector <contestant> rest;

    for (contestant c : A)
    {
        sumHappiness += min(c.s, aSlices) * c.a;
        if (aSlices < c.s) rest.pb({c.s - aSlices, c.a, c.b});
        aSlices -= min(c.s, aSlices);
    }
    for (contestant c : B)
    {
        sumHappiness += min(c.s, bSlices) * c.b;
        if (bSlices < c.s) rest.pb({c.s - bSlices, c.a, c.b});
        bSlices -= min(c.s, bSlices);
    }

    for (contestant c : rest)
    {
        if (aSlices)
        {
            sumHappiness += min(aSlices, c.s) * c.a;
            aSlices -= min(c.s, aSlices);
        } else
        {
            sumHappiness += min(bSlices, c.s) * c.b;
            bSlices -= min(c.s, bSlices);
        }
    }

    return sumHappiness;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	#ifndef ONLINE_JUDGE
        freopen("B.txt", "r", stdin);
	#endif // ONLINE_JUDGE

    cin >> N >> S;
    llong totalSlices = 0, ai, bi, si;;
    REPN(i, N)
    {
        cin >> si >> ai >> bi;
        totalSlices += si;
        if (ai > bi) A.pb({si, ai, bi});
        else B.pb({si, ai, bi});
    }

    sort(A.begin(), A.end(), compByA);
    sort(B.begin(), B.end(), compByB);
    nPizza = (totalSlices + S - 1LL) / S;

    llong low = 0, high = nPizza, mid;
    while (low < high)
    {
        mid = (low + high + 1) / 2;
        if (maxHappiness(mid) >= maxHappiness(mid - 1))
            low = mid;
        else high = mid - 1;
    }

    llong res = 0;
    for (llong t = max(0LL,low - 50); t <= min(nPizza,low + 50); t++)
    {
        res = max(res, maxHappiness(t));
    }
    //cout << maxHappiness(low) << endl;
    cout << res << endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define REPN(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a, _b = b; i <= _b; ++i)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define sz(a) (int)a.size()

typedef pair<int, int> pii;
typedef vector<int> vi;
typedef long long llong;

const int maxN = 100005;

struct contestant  { int s, a, b;};
bool compByA(contestant x, contestant y) { return x.a > y.a; }
bool compByB(contestant x, contestant y) { return x.b > y.b; }

int a[maxN], b[maxN], s[maxN], N, S, nPizza;
vector <contestant> A, B;

llong maxHappiness(int typeA)
{
    int aSlices = typeA * S, bSlices = (nPizza - typeA) * S;
    llong sumHappiness = 0;
    vector <contestant> rest;

    for (contestant c : A)
    {
        sumHappiness += 1LL * min(c.s, aSlices) * c.a;
        if (aSlices < c.s) rest.pb({c.s - aSlices, c.a, c.b});
        aSlices -= min(c.s, aSlices);
    }
    for (contestant c : B)
    {
        sumHappiness += 1LL * min(c.s, bSlices) * c.b;
        if (bSlices < c.s) rest.pb({c.s - bSlices, c.a, c.b});
        bSlices -= min(c.s, bSlices);
    }
    for (contestant c : rest)
    {
        if (aSlices)
        {
            sumHappiness += 1LL * min(aSlices, c.s) * c.a;
            aSlices -= min(c.s, aSlices);
        } else
        {
            sumHappiness += 1LL * min(bSlices, c.s) * c.b;
            bSlices -= min(c.s, bSlices);
        }
    }

    return sumHappiness;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	#ifndef ONLINE_JUDGE
        freopen("B.txt", "r", stdin);
	#endif // ONLINE_JUDGE
    cin >> N >> S;
    int totalSlices = 0;
    REPN(i, N)
    {
        cin >> s[i] >> a[i] >> b[i];
        totalSlices += s[i];
        if (a[i] > b[i]) A.pb({s[i], a[i], b[i]});
        else B.pb({s[i], a[i], b[i]});
    }
    sort(A.begin(), A.end(), compByA);
    sort(B.begin(), B.end(), compByB);

    nPizza = (totalSlices + S - 1) / S;

//    for (int typeA = 0; typeA <= nPizza; typeA++)
//    {
//        int typeB = nPizza - typeA;
//        cout << typeA << " " << typeB << " : "
//            << maxHappiness(typeA * S, typeB * S) << "\n";
//    }

    int low = 0, high = nPizza, mid;
    while (low < high)
    {
        mid = (low + high + 1) / 2;
        if (maxHappiness(mid) >= maxHappiness(mid - 1))
            low = mid;
        else high = mid - 1;
    }
    cout << maxHappiness(low) << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long llong;

const int maxN = 100005;
int N;
llong S, s[maxN], a[maxN], b[maxN];
vector < pair <llong, llong> > A, B;

int main()
{
  ios_base::sync_with_stdio(false);

  cin >> N >> S;
  llong totalSlices = 0, sliceA = 0, sliceB = 0, ans = 0;
  for (int i = 0; i < N; ++i)
  {
    cin >> s[i] >> a[i] >> b[i];
    totalSlices += s[i];
    ans += max(a[i], b[i]) * s[i];
    if (a[i] > b[i])
      A.push_back({a[i] - b[i], s[i]}), sliceA += s[i];
    else
      B.push_back({b[i] - a[i], s[i]}), sliceB += s[i];
  }

  llong nPizza = (totalSlices + S - 1) / S;
  B.push_back({0, S * nPizza - totalSlices});
  sliceB += (S * nPizza - totalSlices);

  sort(A.begin(), A.end());
  sort(B.begin(), B.end());

  llong delta, minDelta, r;

  delta = 0, r = sliceA % S;
  for (pair <llong, llong> contestant : A)
  {
    llong change = min(r, contestant.second);
    r -= change;
    delta += change * contestant.first;
  }
  minDelta = delta;

  delta = 0, r = sliceB % S;
  for (pair <llong, llong> contestant : B)
  {
    llong change = min(r, contestant.second);
    r -= change;
    delta += change * contestant.first;
  }
  minDelta = min(minDelta, delta)  ;

  cout << ans - minDelta << endl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define REPN(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a, _b = b; i <= _b; ++i)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define sz(a) (int)a.size()

typedef pair<int, int> pii;
typedef vector<int> vi;
typedef long long llong;

const int maxN = 100005;

struct contestant  { int s, a, b;};
bool compByA(contestant x, contestant y) { return x.a > y.a; }
bool compByB(contestant x, contestant y) { return x.b > y.b; }

int a[maxN], b[maxN], s[maxN], N, S, nPizza;
vector <contestant> A, B;

llong maxHappiness(int typeA)
{
    int aSlices = typeA * S, bSlices = (nPizza - typeA) * S, sumHappiness = 0;
    vector <contestant> rest;

    for (contestant c : A)
    {
        sumHappiness += 1LL * min(c.s, aSlices) * c.a;
        if (aSlices < c.s) rest.pb({c.s - aSlices, c.a, c.b});
        aSlices -= min(c.s, aSlices);
    }
    for (contestant c : B)
    {
        sumHappiness += 1LL * min(c.s, bSlices) * c.b;
        if (bSlices < c.s) rest.pb({c.s - bSlices, c.a, c.b});
        bSlices -= min(c.s, bSlices);
    }
    for (contestant c : rest)
    {
        if (aSlices)
        {
            sumHappiness += 1LL * min(aSlices, c.s) * c.a;
            aSlices -= min(c.s, aSlices);
        } else
        {
            sumHappiness += 1LL * min(bSlices, c.s) * c.b;
            bSlices -= min(c.s, bSlices);
        }
    }

    return sumHappiness;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	#ifndef ONLINE_JUDGE
        freopen("B.txt", "r", stdin);
	#endif // ONLINE_JUDGE
    cin >> N >> S;
    int totalSlices = 0;
    REPN(i, N)
    {
        cin >> s[i] >> a[i] >> b[i];
        totalSlices += s[i];
        if (a[i] > b[i]) A.pb({s[i], a[i], b[i]});
        else B.pb({s[i], a[i], b[i]});
    }
    sort(A.begin(), A.end(), compByA);
    sort(B.begin(), B.end(), compByB);

    nPizza = (totalSlices + S - 1) / S;

    int low = 0, high = nPizza, mid;
    while (low < high)
    {
        mid = (low + high + 1) / 2;
        if (maxHappiness(mid) >= maxHappiness(mid - 1))
            low = mid;
        else high = mid - 1;
    }
    cout << maxHappiness(low) << endl;

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) < 0.00000000000001) continue;
				else {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) >= 0.0000000000000000000000000000001) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) < 0.0000000001) continue;
				else {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002
#define ERRO 1e-21

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((p.x - i)*(p.x - i) + (p.y - j)*(p.y - j) <= d*d + ERRO) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) < 0.000000000000000000000000000000001) continue;
				else {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002
#define ERRO 1e-15

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((p.x - i)*(p.x - i) + (p.y - j)*(p.y - j) <= d*d + ERRO) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) < 0.0000000000000000000001) continue;
				else {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if(sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) <= (double) d){
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) >= 0.00000000000000000000000000001) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002
#define ERRO 1e-9

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((p.x - i)*(p.x - i) + (p.y - j)*(p.y - j) <= d*d + ERRO) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002
#define ERRO 1e-31

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((p.x - i)*(p.x - i) + (p.y - j)*(p.y - j) <= d*d + ERRO) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((p.x - i)*(p.x - i) + (p.y - j)*(p.y - j) <= d*d) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				if((double) d - sqrt(pow(p.x - i, 2) + pow(p.y - j, 2)) >= 0.0000000001) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	if(vp.empty()) res = -1;
	else {
		lup(i, 0, q) {
			c = tolower(text[i]);
			aux = ((int)c) - 97;
			if(letras[aux] == -1) {
					res = -1;
					break;
				}
			if(c != text[i] and letras[aux] == 0) res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


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

#define x first
#define y second
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<ll> vll;
#define lup(x,a,b) for(int x = a; x < b; x++)
#define ldown(y,a,b) for(int y = a; y >= b; y--)
#define MAXN 100002
#define ERRO 1e-7

int n, m, d, aux, letras[27], q, res = 0;
vector <pii> vp;
pii p;
char mat[51][51], c, text[MAXN];
//bool chk[51][51];

int main()
{
	memset(letras, -1, sizeof(letras));
	scanf("%d %d %d", &n, &m, &d);

	gets(&c);
	lup(i, 0, n) {
		lup(j, 0, m) {
			scanf("%c", &c);
			if(c != 'S') {
				aux = ((int)c) - 97;
				letras[aux] = 0;
			}
			else {
				p.x = i;
				p.y = j;
				vp.push_back(p);
			}
			mat[i][j] = c;
		}
		gets(&c);
	}

	lup(k, 0, (int) vp.size()) { //p cada 'S'
		p.x = vp[k].x;
		p.y = vp[k].y;
		lup(i, p.x - d, p.x + d + 1) {
			lup(j, p.y - d, p.y + d + 1) {
				int a = p.x - i, b = p.y - j;
				if(a*a + b*b <= d*d) {
					if(i >= 0 and j >= 0 and i < n and j < m) {
						if(mat[i][j]!= 'S') {
							aux = ((int)mat[i][j]) - 97;
							letras[aux] = 1;
						}
					}
				}
			}
		}
	}
	scanf("%d", &q);
	gets(&c);
	scanf("%s", text);
	lup(i, 0, q) {
		c = tolower(text[i]);
		aux = ((int)c) - 97;
		if(res == -1) break;
		if(letras[aux] == -1) res = -1;
		else if(c != text[i] and letras[aux] == 0) {
			if(vp.empty()) res = -1;
			else res++;
		}
	}
	printf("%d\n", res);

    return 0;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include <queue>
#include<iomanip>
#include<set>
#include<map>
using namespace std;
#define loop(i,n) for(int i = 0,_ = (n);i < _;i++)
#define lp(i,m,n) for(int i=m;i<n;i++)
#define all(v) v.begin(),v.end()
#define omani dance();
#define sortva(v) sort(all(v))
#define sortvd(v) sort(v.rbegin(),v.rend())
#define sortaa(a,n) sort(a,a+n)
#define sz(v) (int)v.size()
#define uq(c) (c).resize(unique(all(c)) - (c).begin())
typedef long long ll;
#define clr(v,val) memset(v,val,sizeof v)
int dx[] = { 0, 0, 1, -1, 1, -1, 1, -1 };
int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 };

ll gcd(ll a, ll b) { return !b ? a : gcd(b, a % b); }
ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b; }
void dance()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

bool comp(pair<int, int>x, pair<int, int>y)
{
	if (x.first == y.first) return x.second<y.second;
	return x.first>y.first;
}
void PLAY() {

	//	freopen("input.txt", "r", stdin);
	//	freopen("output.txt", "w", stdout);

	cout << fixed << setprecision(15);
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}
string s; ll n;

double eq(int x1, int y1, int x2, int y2)
{
	double dis;
	dis = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
	dis = sqrt(dis);
	return dis;
}
bool up(string s)
{
	for (int i = 0; i < s.size(); i++)
	{
		if (isupper(s[i]))return 1;
	}
	return 0;
}
vector <int> node[200000 + 9];
int main()
{
	omani
		int n, m;double  x;
	vector<vector<int>>vv(250);
	cin >> n >> m >> x; bool f = 0; int c = 0;
	map<string, pair<int, int>>mp; string str = ""; string s;
	char ch;
	for (int i = 1; i <=n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			cin >> ch;

			if (ch == 'S')
			{
				f = 1;

				str += "S";
				mp[str]=make_pair(i, j);
			}
			else
				vv[int(ch)].push_back(i), vv[int(ch)].push_back(j);
		}

	}
	int llll; cin >> llll;
	int ans = 0;
	cin >> s;
	if (!f)
		return cout << -1, 0;
	if (!up(s))
		return cout << 0, 0;

	bool as = 0;

	for (int i = 0; i < s.size(); i++)
	{
		double mn = 9999999.9; double mnn = 9999999.9;
		if (isupper(s[i]))
		{
			as = 0;
			for (int j = 0; j < vv[int(tolower(int(s[i])))].size(); j += 2)
			{
				if (as == 1)break;
				string r = str;
				for (int k = 0; k < str.size(); k++)
				{
					double dd = eq(mp[r].first, mp[r].second, vv[int(tolower(int(s[i])))][j], vv[int(tolower(int(s[i])))][j + 1]);
					if (dd < mn)
						mn = dd;
					r.pop_back();
				}
				if (mnn > mn)
				{
					mnn = mn;
				}

			}
			if (mnn > x)
			{
				ans++;
			}
		}
	}
	cout << ans;

	return 0;
}