#include<bits/stdc++.h>
#define ll long long int
#define dd double
/**Define file I/O **/
#define f_input freopen("input.txt","r",stdin)
#define f_output freopen("output.txt","w",stdout)
/**Define memory set function**/
#define mem(x,y) memset(x,y,sizeof(x))
/**Define function and object**/
#define SQR(x) ((x)*(x))
#define DIS(a,b,c,d) sqrt(SQR(a-c)+SQR(b-d))
/**Define constant value**/
#define pi  (2.0*acos(0.0))///3.141592653589793
#define pb push_back
#define mp make_pair
#define nln printf("\n") ///newline
#define Case printf("Case %d:",++cno) ///print case
#define space printf(" ") ///print space
#define tc int t,cno=0;scanf("%d",&t); ///input test case
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
/** priority_queue<int,vector<int>, prioritycom > pq **/
using namespace std;
///ordered set
/**#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T> using orderset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
**/
/**Template & structure**/
struct prioritycom{bool operator()(const int& l, const int& r){return l < r;}};/// priority queue compare function
template<typename T>T lcm(T a, T b){return a / __gcd(a,b) * b;}
template <class T> inline T bigmod(T p,T e,T M){T ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;}return (T)ret;}
template <class string> ll strton(string s){ll won;stringstream ss;ss<<s;ss>>won;return won;}/// convert string to number
template <class T> string ntostr(T n){stringstream ss;ss << n;return ss.str();}/// convert a number to string
template<class T> inline T mod(T n,T m){return (n%m+m)%m;}   ///For Positive Negative No.
template<class T> bool isprime(T n){if(n%2==0){if(n==2)return true;else return false;}T m=sqrt(n);for(T i=3; i<=m; i+=2){if(n%i==0)return false;}return true;}
bool isvowel(char ch){ch=toupper(ch);if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true;return false;}
dd triangle_area1(dd a, dd b, dd c){dd s=(a+b+c)*0.5; return sqrt(s*(s-a)*(s-b)*(s-c));} ///with s
dd triangle_area2(dd x1,dd y1, dd x2, dd y2, dd x3, dd y3){ return 0.5*abs(x1*y2+x2*y3+x3*y1-x2*y1-x3*y2-x1*y3);}///with points.must be in anticlockwise
dd circle_area(dd r ,dd theta) {return (theta*pi*r*r)/(2*pi);} ///area of circle sector with center angle theta.theta needs to be radian.
dd quad_area(dd x1,dd y1, dd x2, dd y2, dd x3, dd y3, dd x4, dd y4){ return 0.5*abs(x1*y2+x2*y3+x3*y4+x4*y1-x2*y1-x3*y2-x4*y3-x1*y4);}///with points.must be in anticlockwise
dd cosangle(dd a,dd b, dd c){return acos((dd)(b*b+c*c-a*a)/(dd)(2*b*c));}///calculate angle from three sides of a triangle. returns angle in radian
///void stow(string s){stringstream ss(s);string x;while(ss>>x){cout<<x<<endl;}} sentence to word
ll Set(ll N,ll pos){return N=N | (1ll<<pos);}
ll reset(ll N,ll pos){return N= N & ~(1ll<<pos);}
bool check(ll N,ll pos){return (bool)(N & (1ll<<pos));}
#define M 1000000007
#define MX 100005
/**
ll day_of_months[]={31,28,31,30,31,30,31,31,30,31,30,31};
ll knight_X[ ] = { 1, 1, 2, 2, -1, -1, -2, -2 };
ll knight_Y[ ] = { 2, -2, 1, -1, 2, -2, 1, -1 };
ll dx8[]={-1,-1,-1,0,0,1,1,1};
ll dy8[]={-1,0,1,-1,1,-1,0,1};
ll dx4[]={-1,0,1,0};
ll dy4[]={0,1,0,-1};
**/
/******************************End******************************/
ll cost[MX],cap[MX],x[MX],t,T,m,n,ans=0,inf=999999999999999;
ll calc(ll b, ll i)
{
    ll r=b*cost[i];
    if(m-b*cap[i]<=0)
        return r;
    r+=((m-b*cap[i])+cap[i])*x[i];
    return r;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(ll i=1;i<=n;i++)
    {
        scanf("%lld%lld%lld%lld",&t,&T,&x[i],&cost[i]);
        cap[i]=max(0ll,T-t);
        ll lo=1,hi=m,mid,cur=calc(m,i),xx;
        while(lo<=hi)
        {
            mid=(lo+hi)/2;
            if(calc(mid,i)<=cur)
            {
                xx=mid;
                cur=calc(mid,i);
                hi=mid-1;
            }
            else lo=mid+1;
        }
       // cout<<cur<<" "<<xx<<endl;
        ans+=cur;
    }
    printf("%lld\n",ans);

}


#include<bits/stdc++.h>
#define ll long long int
#define dd double
/**Define file I/O **/
#define f_input freopen("input.txt","r",stdin)
#define f_output freopen("output.txt","w",stdout)
/**Define memory set function**/
#define mem(x,y) memset(x,y,sizeof(x))
/**Define function and object**/
#define SQR(x) ((x)*(x))
#define DIS(a,b,c,d) sqrt(SQR(a-c)+SQR(b-d))
/**Define constant value**/
#define pi  (2.0*acos(0.0))///3.141592653589793
#define pb push_back
#define mp make_pair
#define nln printf("\n") ///newline
#define Case printf("Case %d:",++cno) ///print case
#define space printf(" ") ///print space
#define tc int t,cno=0;scanf("%d",&t); ///input test case
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
/** priority_queue<int,vector<int>, prioritycom > pq **/
using namespace std;
///ordered set
/**#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T> using orderset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
**/
/**Template & structure**/
struct prioritycom{bool operator()(const int& l, const int& r){return l < r;}};/// priority queue compare function
template<typename T>T lcm(T a, T b){return a / __gcd(a,b) * b;}
template <class T> inline T bigmod(T p,T e,T M){T ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;}return (T)ret;}
template <class string> ll strton(string s){ll won;stringstream ss;ss<<s;ss>>won;return won;}/// convert string to number
template <class T> string ntostr(T n){stringstream ss;ss << n;return ss.str();}/// convert a number to string
template<class T> inline T mod(T n,T m){return (n%m+m)%m;}   ///For Positive Negative No.
template<class T> bool isprime(T n){if(n%2==0){if(n==2)return true;else return false;}T m=sqrt(n);for(T i=3; i<=m; i+=2){if(n%i==0)return false;}return true;}
bool isvowel(char ch){ch=toupper(ch);if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true;return false;}
dd triangle_area1(dd a, dd b, dd c){dd s=(a+b+c)*0.5; return sqrt(s*(s-a)*(s-b)*(s-c));} ///with s
dd triangle_area2(dd x1,dd y1, dd x2, dd y2, dd x3, dd y3){ return 0.5*abs(x1*y2+x2*y3+x3*y1-x2*y1-x3*y2-x1*y3);}///with points.must be in anticlockwise
dd circle_area(dd r ,dd theta) {return (theta*pi*r*r)/(2*pi);} ///area of circle sector with center angle theta.theta needs to be radian.
dd quad_area(dd x1,dd y1, dd x2, dd y2, dd x3, dd y3, dd x4, dd y4){ return 0.5*abs(x1*y2+x2*y3+x3*y4+x4*y1-x2*y1-x3*y2-x4*y3-x1*y4);}///with points.must be in anticlockwise
dd cosangle(dd a,dd b, dd c){return acos((dd)(b*b+c*c-a*a)/(dd)(2*b*c));}///calculate angle from three sides of a triangle. returns angle in radian
///void stow(string s){stringstream ss(s);string x;while(ss>>x){cout<<x<<endl;}} sentence to word
ll Set(ll N,ll pos){return N=N | (1ll<<pos);}
ll reset(ll N,ll pos){return N= N & ~(1ll<<pos);}
bool check(ll N,ll pos){return (bool)(N & (1ll<<pos));}
#define M 1000000007
#define MX 100005
/**
ll day_of_months[]={31,28,31,30,31,30,31,31,30,31,30,31};
ll knight_X[ ] = { 1, 1, 2, 2, -1, -1, -2, -2 };
ll knight_Y[ ] = { 2, -2, 1, -1, 2, -2, 1, -1 };
ll dx8[]={-1,-1,-1,0,0,1,1,1};
ll dy8[]={-1,0,1,-1,1,-1,0,1};
ll dx4[]={-1,0,1,0};
ll dy4[]={0,1,0,-1};
**/
/******************************End******************************/
ll cost[MX],cap[MX],x[MX],t,T,m,n,ans=0,inf=999999999999999999;
ll calc(ll b, ll i)
{
    ll r=b*cost[i];
    if(m-b*cap[i]<=0)
        return r;
    r+=((m-b*cap[i])+cap[i])*x[i];
    return r;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(ll i=1;i<=n;i++)
    {
        scanf("%lld%lld%lld%lld",&t,&T,&x[i],&cost[i]);
        cap[i]=max(0ll,T-t);
        ll lo=1,hi=m,mid,cur=calc(m,i),xx;
        while(lo<=hi)
        {
            mid=(lo+hi)/2;
            if(calc(mid,i)<=cur)
            {
                xx=mid;
                cur=calc(mid,i);
                hi=mid-1;
            }
            else lo=mid+1;
        }
       // cout<<cur<<" "<<xx<<endl;
        ans+=cur;
    }
    printf("%lld\n",ans);
}


#include<bits/stdc++.h>
#define ll long long int
#define dd double
/**Define file I/O **/
#define f_input freopen("input.txt","r",stdin)
#define f_output freopen("output.txt","w",stdout)
/**Define memory set function**/
#define mem(x,y) memset(x,y,sizeof(x))
/**Define function and object**/
#define SQR(x) ((x)*(x))
#define DIS(a,b,c,d) sqrt(SQR(a-c)+SQR(b-d))
/**Define constant value**/
#define pi  (2.0*acos(0.0))///3.141592653589793
#define pb push_back
#define mp make_pair
#define nln printf("\n") ///newline
#define Case printf("Case %d:",++cno) ///print case
#define space printf(" ") ///print space
#define tc int t,cno=0;scanf("%d",&t); ///input test case
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
/** priority_queue<int,vector<int>, prioritycom > pq **/
using namespace std;
///ordered set
/**#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T> using orderset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
**/
/**Template & structure**/
struct prioritycom{bool operator()(const int& l, const int& r){return l < r;}};/// priority queue compare function
template<typename T>T lcm(T a, T b){return a / __gcd(a,b) * b;}
template <class T> inline T bigmod(T p,T e,T M){T ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;}return (T)ret;}
template <class string> ll strton(string s){ll won;stringstream ss;ss<<s;ss>>won;return won;}/// convert string to number
template <class T> string ntostr(T n){stringstream ss;ss << n;return ss.str();}/// convert a number to string
template<class T> inline T mod(T n,T m){return (n%m+m)%m;}   ///For Positive Negative No.
template<class T> bool isprime(T n){if(n%2==0){if(n==2)return true;else return false;}T m=sqrt(n);for(T i=3; i<=m; i+=2){if(n%i==0)return false;}return true;}
bool isvowel(char ch){ch=toupper(ch);if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true;return false;}
dd triangle_area1(dd a, dd b, dd c){dd s=(a+b+c)*0.5; return sqrt(s*(s-a)*(s-b)*(s-c));} ///with s
dd triangle_area2(dd x1,dd y1, dd x2, dd y2, dd x3, dd y3){ return 0.5*abs(x1*y2+x2*y3+x3*y1-x2*y1-x3*y2-x1*y3);}///with points.must be in anticlockwise
dd circle_area(dd r ,dd theta) {return (theta*pi*r*r)/(2*pi);} ///area of circle sector with center angle theta.theta needs to be radian.
dd quad_area(dd x1,dd y1, dd x2, dd y2, dd x3, dd y3, dd x4, dd y4){ return 0.5*abs(x1*y2+x2*y3+x3*y4+x4*y1-x2*y1-x3*y2-x4*y3-x1*y4);}///with points.must be in anticlockwise
dd cosangle(dd a,dd b, dd c){return acos((dd)(b*b+c*c-a*a)/(dd)(2*b*c));}///calculate angle from three sides of a triangle. returns angle in radian
///void stow(string s){stringstream ss(s);string x;while(ss>>x){cout<<x<<endl;}} sentence to word
ll Set(ll N,ll pos){return N=N | (1ll<<pos);}
ll reset(ll N,ll pos){return N= N & ~(1ll<<pos);}
bool check(ll N,ll pos){return (bool)(N & (1ll<<pos));}
#define M 1000000007
#define MX 100005
/**
ll day_of_months[]={31,28,31,30,31,30,31,31,30,31,30,31};
ll knight_X[ ] = { 1, 1, 2, 2, -1, -1, -2, -2 };
ll knight_Y[ ] = { 2, -2, 1, -1, 2, -2, 1, -1 };
ll dx8[]={-1,-1,-1,0,0,1,1,1};
ll dy8[]={-1,0,1,-1,1,-1,0,1};
ll dx4[]={-1,0,1,0};
ll dy4[]={0,1,0,-1};
**/
/******************************End******************************/
ll cost[MX],cap[MX],x[MX],t,T,m,n,ans=0,inf=999999999999999;
ll calc(ll b, ll i)
{
    ll r=b*cost[i];
    if(m-b*cap[i]<=0)
        return r;
    r+=((m-b*cap[i])+cap[i])*x[i];
    return r;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(ll i=1;i<=n;i++)
    {
        scanf("%lld%lld%lld%lld",&t,&T,&x[i],&cost[i]);
        cap[i]=max(0ll,T-t);

        ll cur=calc(1,i);
        if(cap[i])
        {
            ll xx=m/cap[i];
            if(m%cap[i])
            xx++;
            cur=min(cur,calc(xx,i));
        }
        ans+=cur;
    }
    printf("%lld\n",ans);
}


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

 #define ll long long
 #define pb push_back
 #define fi first
 #define se second
 #define FILE ""
 #define ull unsigned long long
 #define ld long double
 #define rev reverse
 #define pob pop_back()
 #define sz size()
 #define bb begin()
 #define ee end()

 int main()
 {
     ios_base::sync_with_stdio(false);cin.tie(0), cout.tie(0);
     /*freopen(FILE ".in", "r", stdin);
     freopen(FILE ".out", "w", stdout);*/
     int n,m;
     cin >> n >> m;
     ll t[n],T[n],x[n],a[n];
     ll ans1=0;
     for(int i=0;i<n;i++)
     {
        cin >> t[i] >> T[i] >> x[i] >> a[i];
        if(T[i]<=t[i])
        {
           ans1+=(m*x[i]);
        }
        else
        {
           ll q=ceil((double)m/(T[i]-t[i]));
           ll w=a[i];
           if(m>(T[i]-t[i]))
           {
              w+=(m*x[i]);

           }
           ans1+=min(q*a[i],w);
        }
        //cout << ans1 << endl;
     }
     cout << ans1;
     return 0;
 }


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

 #define ll long long
 #define pb push_back
 #define fi first
 #define se second
 #define FILE ""
 #define ull unsigned long long
 #define ld long double
 #define rev reverse
 #define pob pop_back()
 #define sz size()
 #define bb begin()
 #define ee end()

 int main()
 {
     ios_base::sync_with_stdio(false);cin.tie(0), cout.tie(0);
     /*freopen(FILE ".in", "r", stdin);
     freopen(FILE ".out", "w", stdout);*/
     int n,m;
     cin >> n >> m;
     ll t[n],T[n],x[n],a[n];
     ll ans1=0;
     for(int i=0;i<n;i++)
     {
        cin >> t[i] >> T[i] >> x[i] >> a[i];
        if(T[i]<=t[i])
        {
           ans1+=(m*x[i]+a[i]);
        }
        else
        {
           ll q=ceil((double)m/(T[i]-t[i]));
           ll w=a[i];
           if(m>(T[i]-t[i]))
           {
              w+=(m*x[i]);

           }
           ans1+=min(q*a[i],w);
        }
        //cout << ans1 << endl;
     }
     cout << ans1;
     return 0;
 }


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #include <ext/pb_ds/detail/standard_policies.hpp>
using namespace std;
using namespace __gnu_pbds;
// const ll RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count();
// gp_hash_table<int, int> table;

#define ll long long int
#define vii vector< ll >
#define pb push_back
#define pii pair<ll,ll>
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define ins insert
#define ld long double
#define lp(l,r) for(i=l;i<=r;++i)

#define lpj(l,r) for(j=l;j<=r;++j)
#define lpr(l,r) for(i=r;i>=l;--i)
#define lprj(l,r) for(j=r;j>=l;--j)

#define swap(a,b){ auto _t=a;a=b,b=_t;}
#define flush() cout.flush()
#define popcount __builtin_popcount
#define die() return 0;

// typedef __int128 bign;

#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

#define MD          1000000007
#define M 			200011
#define LN 			14
#define fftmod      998244353
#define EPS         (double)1e-10

ll md=MD;
ll inf=1e18;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

inline ll exp(ll a,ll b){ll r=1LL;while(b>0){if(b&1){r=r*(a%md);r=(r+md)%md;}b/=2;a=(a%md)*(a%md);a=(a+md)%md;}return (r+md)%md;}
ll gcd(ll a,ll b){if(b==0)return a;if(a==0)return b;return gcd(b,a%b);}
inline ll poww(ll a,ll b){ll r=1LL;while(b>0){if(b&1)r=r*a;b/=2;a=a*a;}return (ll)r;}

using cd=complex<double>;
const double PI=acos(-1);

inline ll rand(ll l,ll r){
	return l+rng()%(r-l+1);
}
ll a[M],T[M],c[M],b[M];

int main(){

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

   // ifstream fin("input.txt");ofstream fout("outut.txt");
    ll t,i,j,m,n,s,z,k,p;string s1,s2;ll q;ll x,y;
    cin>>n>>m;
    lp(1,n){
    	cin>>a[i]>>T[i]>>b[i]>>c[i];
    }
    p=0;
    lp(1,n){
    	k=T[i]-a[i];
    	ll c1=(m/k)*c[i];
    	if(m%k)c1+=c[i];
    	ll c2=c[i];
    	if(a[i]+m>T[i])c2=b[i]*m+c[i];
    	p+=min(c1,c2);
    }
    cout<<p<<"\n";

}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #include <ext/pb_ds/detail/standard_policies.hpp>
using namespace std;
using namespace __gnu_pbds;
// const ll RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count();
// gp_hash_table<int, int> table;

#define ll long long int
#define vii vector< ll >
#define pb push_back
#define pii pair<ll,ll>
#define all(x) x.begin(),x.end()
#define S second
#define F first
#define ins insert
#define ld long double
#define lp(l,r) for(i=l;i<=r;++i)

#define lpj(l,r) for(j=l;j<=r;++j)
#define lpr(l,r) for(i=r;i>=l;--i)
#define lprj(l,r) for(j=r;j>=l;--j)

#define swap(a,b){ auto _t=a;a=b,b=_t;}
#define flush() cout.flush()
#define popcount __builtin_popcount
#define die() return 0;

// typedef __int128 bign;

#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

#define MD          1000000007
#define M 			200011
#define LN 			14
#define fftmod      998244353
#define EPS         (double)1e-10

ll md=MD;
ll inf=1e18;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

inline ll exp(ll a,ll b){ll r=1LL;while(b>0){if(b&1){r=r*(a%md);r=(r+md)%md;}b/=2;a=(a%md)*(a%md);a=(a+md)%md;}return (r+md)%md;}
ll gcd(ll a,ll b){if(b==0)return a;if(a==0)return b;return gcd(b,a%b);}
inline ll poww(ll a,ll b){ll r=1LL;while(b>0){if(b&1)r=r*a;b/=2;a=a*a;}return (ll)r;}

using cd=complex<double>;
const double PI=acos(-1);

inline ll rand(ll l,ll r){
	return l+rng()%(r-l+1);
}
ll a[M],T[M],c[M],b[M];

int main(){

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

   // ifstream fin("input.txt");ofstream fout("outut.txt");
    ll t,i,j,m,n,s,z,k,p;string s1,s2;ll q;ll x,y;
    cin>>n>>m;
    lp(1,n){
    	cin>>a[i]>>T[i]>>b[i]>>c[i];
    }
    p=0;
    lp(1,n){
    	k=T[i]-a[i];
    	ll c1;
    	ll c2=c[i];
    	if(a[i]+m>T[i])c2=b[i]*m+c[i];
    	if(k<=0){p+=c2;continue;}
    	c1=(m/k)*c[i];
    	if(m%k)c1+=c[i];
    	p+=min(c1,c2);
    }
    cout<<p<<"\n";

}


/////////////////////////   _LeMur_
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#define _CRT_SECURE_NO_WARNINGS
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cassert>
#include <chrono>
#include <random>
#include <bitset>
#include <cstdio>
#include <vector>
#include <string>
#include <ctime>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <list>
#include <map>
#include <set>

using namespace std;

const int N = 100005;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;

int n, m;

int main(){
    cin >> n >> m;
    long long answ = 0;
    for(int i=1;i<=n;i++){
        int t , T , x , c;
        scanf("%d%d%d%d",&t,&T,&x,&c);
        if(t < T){
            int s = (m + T - t - 1) / (T - t);
            answ += min( c + m * 1ll * x , s * 1ll * c );
        }
        else
            answ += c + m * 1ll * x;
    }
    cout << answ << endl;
    return 0;
}


/////////////////////////   _LeMur_
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#define _CRT_SECURE_NO_WARNINGS
#include <unordered_map>
#include <unordered_set>
#include <functional>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cassert>
#include <chrono>
#include <random>
#include <bitset>
#include <cstdio>
#include <vector>
#include <string>
#include <ctime>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <list>
#include <map>
#include <set>

using namespace std;

const int N = 100005;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;

int n, m;

int main(){
    cin >> n >> m;
    long long answ = 0;
    for(int i=1;i<=n;i++){
        int t , T , x , c;
        scanf("%d%d%d%d",&t,&T,&x,&c);
        if(t != T){
            int s = (m + T - t - 1) / (T - t);
            answ += min( c + m * 1ll * x , s * 1ll * c );
        }
        else
            answ += c + m * 1ll * x;
    }
    cout << answ << endl;
    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdlib>
#include <string>
#include <map>
using namespace std;
#define INF 0x7fffffffffffffff
#define LL long long
#define fi first
#define se second
#define mem(a,b) memset((a),(b),sizeof(a))
#define sqr(x) ((x)*(x))

int N, M;
LL t, T, x, cost;

inline LL judge(LL n)
{
    return cost*n+(M-(T-t)*(n-1))*x;
}

int main()
{
    scanf("%d%d", &N, &M);
    LL ans=0;
    for(int i=0;i<N;++i)
    {
        scanf("%lld%lld%lld%lld", &t, &T, &x, &cost);
        if(T<=t)
        {
            ans+=cost+x*M;
            continue;
        }
        LL n=(M+T-t-1)/(T-t);
        LL the_min=n*cost;
        LL l=1, r=n-1;
        while(r-l>=2)
        {
            LL mid=(l+r)>>1;
            LL midmid=(mid+r)>>1;
            if(judge(mid)>judge(midmid))
                l=mid;
            else r=midmid;
        }
        for(LL i=l;i<=r;++i)
            the_min=min(the_min, judge(i));
//        cout<<"the_min: "<<the_min<<endl;
        ans+=the_min;
    }
    printf("%lld\n", ans);

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdlib>
#include <string>
#include <map>
using namespace std;
#define INF 0x7fffffffffffffff
#define LL long long
#define fi first
#define se second
#define mem(a,b) memset((a),(b),sizeof(a))
#define sqr(x) ((x)*(x))

int N, M;
LL t, T, x, cost;

inline LL judge(LL n)
{
    if(n*(T-t)>=M)
        return cost*n;
    else return cost*n+(M-(T-t)*(n-1))*x;
}

int main()
{
    scanf("%d%d", &N, &M);
    LL ans=0;
    for(int i=0;i<N;++i)
    {
        scanf("%lld%lld%lld%lld", &t, &T, &x, &cost);
        if(T<=t)
        {
            ans+=cost+x*M;
            continue;
        }
        int l=1, r=M;
        while(r-l>=2)
        {
            int mid=(l+r)>>1;
            int midmid=(mid+r)>>1;
            if(judge(mid)>judge(midmid))
                l=mid;
            else r=midmid;
        }
        LL the_min=INF;
        for(int i=l;i<=r;++i)
            the_min=min(the_min, judge(i));
//        cout<<"the_min: "<<the_min<<endl;
        ans+=the_min;
    }
    printf("%lld\n", ans);

    return 0;
}


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

#define maxn
#define FOR(i, l, r) for (int i=l; i<=r; ++i)
#define FORD(i, r, l) for (int i=r; i>=l; --i)
#define REP(i, r) for (int i=0; i<(int)r; ++i)
#define REPD(i, r) for (int i=(int)r-1; i>=0; --i)
#define fi first
#define se second
#define mk make_pair
#define nil NULL
#define y0 y902
#define y1 y232
#define x0 x92
#define x1 x899
#define next asdfa
#define sz size
#define Debug(X) {cerr << #X << " = " << X << '\n';}
#define PR(A, n) {cerr << #A << " = "; FOR(i, 1, n) cerr << A[i] << ' '; cerr << '\n';}
#define PR0(A, n) {cerr << #A << " = "; REP(i, n) cerr << A[i] << ' '; cerr << '\n';}
typedef long long ll;
typedef double db;
typedef pair<db, db> dd;
typedef pair<int, int> ii;
typedef vector<int> vi;
const int inf = 1e9;
template<class T> int getbit(T x, int pos) {return (x>>(pos-1)) & 1;}
template<class T> void turn_on(T &x, int pos) {x = x | ((T)1<<(pos-1));}
template<class T> void turn_off(T &x, int pos) {x = x & ~((T)1<<(pos-1));}
template<class T> T sqr(T a) {return a*a;}

int n;
ll M;

ll calc(ll t, ll T, ll x, ll c, ll nBus) {
    if (M-(T-t)*(nBus-1)+t<=T) return nBus*c;
    return nBus*c + max(M-(T-t)*(nBus-1), 0LL)*x;
}

int main() {
    //freopen("hotdays.inp", "r", stdin);
    //freopen("", "w", stdout);
    //ios::sync_with_stdio(0); cin.tie(0);
    scanf("%d%I64d", &n, &M);
    ll res = 0;
    FOR(i, 1, n) {
        ll t, T, x, c; scanf("%I64d %I64d %I64d %I64d", &t, &T, &x, &c);
        if (T<=t) {
            res += (c + M*x);
            continue;
        }
        ll tmp = min(calc(t, T, x, c, 1), calc(t, T, x, c, ceil(db(M)/db(T-t))));
        tmp = min(tmp, calc(t, T, x, c, ceil(db(M)/db(T-t))-1));
        res += tmp;
    }
    printf("%I64d", res);
}


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

#define maxn
#define FOR(i, l, r) for (int i=l; i<=r; ++i)
#define FORD(i, r, l) for (int i=r; i>=l; --i)
#define REP(i, r) for (int i=0; i<(int)r; ++i)
#define REPD(i, r) for (int i=(int)r-1; i>=0; --i)
#define fi first
#define se second
#define mk make_pair
#define nil NULL
#define y0 y902
#define y1 y232
#define x0 x92
#define x1 x899
#define next asdfa
#define sz size
#define Debug(X) {cerr << #X << " = " << X << '\n';}
#define PR(A, n) {cerr << #A << " = "; FOR(i, 1, n) cerr << A[i] << ' '; cerr << '\n';}
#define PR0(A, n) {cerr << #A << " = "; REP(i, n) cerr << A[i] << ' '; cerr << '\n';}
typedef long long ll;
typedef double db;
typedef pair<db, db> dd;
typedef pair<int, int> ii;
typedef vector<int> vi;
const ll inf = 1e18;
template<class T> int getbit(T x, int pos) {return (x>>(pos-1)) & 1;}
template<class T> void turn_on(T &x, int pos) {x = x | ((T)1<<(pos-1));}
template<class T> void turn_off(T &x, int pos) {x = x & ~((T)1<<(pos-1));}
template<class T> T sqr(T a) {return a*a;}

int n;
ll M;

ll calc(ll t, ll T, ll x, ll c, ll nBus) {
    if (nBus<=0) return inf;
    if (M-(T-t)*(nBus-1)+t<=T) return nBus*c;
    return nBus*c + max(M-(T-t)*(nBus-1), 0LL)*x;
}

int main() {
    //freopen("hotdays.inp", "r", stdin);
    //freopen("", "w", stdout);
    //ios::sync_with_stdio(0); cin.tie(0);
    scanf("%d%I64d", &n, &M);
    ll res = 0;
    FOR(i, 1, n) {
        ll t, T, x, c; scanf("%I64d %I64d %I64d %I64d", &t, &T, &x, &c);
        if (T<=t) {
            res += (c + M*x);
            continue;
        }
        ll tmp = min(calc(t, T, x, c, 1), calc(t, T, x, c, ceil(db(M)/db(T-t))));
        tmp = min(tmp, calc(t, T, x, c, ceil(db(M)/db(T-t))-1));
        res += tmp;
    }
    printf("%I64d", res);
}


/*
त्यक्तवाधर्मं च लोभं च
मोहंचो द्यमास्थिता।
युद्ध्यध्वमनहंकारा
यतो धर्मस्ततो जयः।।
*/

#include<bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;
using namespace std;
#define int     long long int
#define ld      long double
#define pb      push_back
#define pa      pair<int,int>
#define v1d     vector<int>
#define v2d     vector<vector<int> >
#define M       1000000009
#define MN      LLONG_MIN
#define MX      LLONG_MAX
#define ff      first
#define ss      second
#define endl    "\n"
#define v1s     vector<string>
#define S(v)    sort(v.begin(),v.end())
#define RS(v)   sort(v.rbegin(),v.rend())
#define R(v)    reverse(v.begin(),v.end())
#define mxpq(T)    priority_queue <T>
#define mnpq(T)    priority_queue<T,vector<T>,greater<T>>
#define T       int tc;cin>>tc;while(tc--)
void Weapons19(){
    cin.sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    #ifndef ONLINE_JUDGE
     freopen("input.txt",  "r",  stdin);
     freopen("output.txt", "w", stdout);
    #endif
}
#define qqq 100005
#define paa pair<int,pa>

int32_t main(){
    Weapons19();
    int n,m;cin>>n>>m;
    int ans=0;//cout<<ans;return 0;
    for(int i=0;i<n;i++){
        int a,b,c,d;cin>>a>>b>>c>>d;
        int s=b-a;
        if(s<=0){ans+=c*m+d;continue;}
        int bus=m/s;
        if(m%s)bus++;
        int k=min(m*c+d,bus*d);
        ans+=k;
        //cout<<ans;
    }
    cout<<ans;

}


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

typedef long long ll;
typedef long double ld;

#define FOR(i,a) for (int i=0;i<(a);++i)
#define FORD(i,a) for (int i=(a)-1;i>=0;i--)
#define FORT(i,a,b) for (int i=(a);i<=(b);++i)
#define FORTD(i,b,a) for (int i=(b);i>=(a);--i)
#define trav(i,v) for (auto i : v)
#define all(v) v.begin(),v.end()
#define ad push_back
#define fr first
#define sc second
#define mpr(a,b) make_pair(a,b)
#define pir pair<int,int>
#define all(v) v.begin(),v.end()
#define make_unique(v) v.erase(unique(all(v)),v.end())
#define fastio ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define popcount __builtin_popcount
#define srng mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define y1 EsiHancagorcRepa

const int N=1e4+6;
const ll MOD=1000*1000*1000+7;

ll baj(ll a,ll b)
{
    if (a%b==0)return a/b;
    return a/b+1;
}
int main()
{
    fastio;
    ll ans=0;
    ll n,m;
    cin>>n>>m;
    FOR(i,n){
        ll T,t,x,cost;
        cin>>T>>t>>x>>cost;
        t-=T;
        if (!t){
            ans+=cost+m*x;
            continue;
        }
        ans+=min(baj(m,t)*cost,cost+m*x);
    }
    cout<<ans<<endl;
    return 0;
}


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

typedef long long ll;
typedef long double ld;

#define FOR(i,a) for (int i=0;i<(a);++i)
#define FORD(i,a) for (int i=(a)-1;i>=0;i--)
#define FORT(i,a,b) for (int i=(a);i<=(b);++i)
#define FORTD(i,b,a) for (int i=(b);i>=(a);--i)
#define trav(i,v) for (auto i : v)
#define all(v) v.begin(),v.end()
#define ad push_back
#define fr first
#define sc second
#define mpr(a,b) make_pair(a,b)
#define pir pair<int,int>
#define all(v) v.begin(),v.end()
#define make_unique(v) v.erase(unique(all(v)),v.end())
#define fastio ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define popcount __builtin_popcount
#define srng mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define y1 EsiHancagorcRepa

const int N=1e4+6;
const ll MOD=1000*1000*1000+7;

ll baj(ll a,ll b)
{
    if (a%b==0)return a/b;
    return a/b+1;
}
int main()
{
    fastio;
    ll ans=0;
    ll n,m;
    cin>>n>>m;
    FOR(i,n){
        ll T,t,x,cost;
        cin>>T>>t>>x>>cost;
        t-=T;
        if (t<=0){
            ans+=cost+m*x;
            continue;
        }
        ans+=min(baj(m,t)*cost,cost+m*x);
    }
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<iterator>
#include<list>
#include<math.h>
#include<cstring>
typedef long long ll;
using namespace std;
void FastInOut()
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL), cout.tie(NULL);
}

int main()
{

	int N,M;
	cin>>N>>M;
	ll Ans = 0 ;
	for(int i=0;i<N;i++)
	{
		ll Sum1 = 0 , Sum2 = 0;
		int t , T , X , Cost;
		cin>>t>>T>>X>>Cost;
		Sum1+=Cost;
		if(t + M > T)
		{
			Sum1+=(X*M);
		}
		int Need = T - t;
		if(!Need)Need++;
		int NumberOfBus = ceil((float)M / Need);

		Sum2+=(NumberOfBus*Cost);

		Ans+=min(Sum1 , Sum2);

	}

	cout<<Ans<<endl;

	return 0 ;

}


#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<iterator>
#include<list>
#include<math.h>
#include<cstring>
typedef long long ll;
using namespace std;
void FastInOut()
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL), cout.tie(NULL);
}

int main()
{

	int N,M;
	cin>>N>>M;
	ll Ans = 0 ;
	for(int i=0;i<N;i++)
	{
		ll Sum1 = 0 , Sum2 = 0;
		int t , T , X , Cost;
		cin>>t>>T>>X>>Cost;
		Sum1+=Cost;
		bool NoCalc = 0;
		if(t >= T)
		{
			NoCalc = 1;
			Sum1+=(X*M);
			Sum2 = INT_MAX;
		}
		else
		{
			if(t + M > T)
			{
				Sum1+=(X*M);
			}
		}
		if(!NoCalc)
		{
			int Need = T - t;
			int NumberOfBus = ceil((float)M / Need);
			Sum2+=(NumberOfBus*Cost);
		}

		Ans+=min(Sum1 , Sum2);

	}

	cout<<Ans<<endl;

	return 0 ;

}


#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<iterator>
#include<list>
#include<math.h>
#include<cstring>
typedef long long ll;
using namespace std;
void FastInOut()
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL), cout.tie(NULL);
}

int main()
{

	ll N,M;
	cin>>N>>M;
	ll Ans = 0 ;
	for(ll i=0;i<N;i++)
	{
		ll Sum1 = 0 , Sum2 = 0;
		ll t , T , X , Cost;
		cin>>t>>T>>X>>Cost;
		Sum1+=Cost;
		bool NoCalc = 0;
		if(t >= T)
		{
			NoCalc = 1;
			Sum1+=(X*M);
			Sum2 = LLONG_MAX;
		}
		else
		{
			if(t + M > T)
			{
				Sum1+=(X*M);
			}
		}
		if(!NoCalc)
		{
			ll Need = T - t;
			ll NumberOfBus = ceil((double)M / Need);
			Sum2+=(NumberOfBus*Cost);
		}

		Ans+=min(Sum1 , Sum2);

	}

	cout<<Ans<<endl;

	return 0 ;

}


#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<iterator>
#include<list>
#include<math.h>
#include<cstring>
typedef long long ll;
using namespace std;
void FastInOut()
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL), cout.tie(NULL);
}

int main()
{

	int N,M;
	cin>>N>>M;
	ll Ans = 0 ;
	for(int i=0;i<N;i++)
	{
		ll Sum1 = 0 , Sum2 = 0;
		int t , T , X , Cost;
		cin>>t>>T>>X>>Cost;
		Sum1+=Cost;
		if(t + M > T)
		{
			Sum1+=(X*M);
		}
		int Need = T - t;
		int NumberOfBus = (M  +  Need - 1 )/ Need;

		Sum2+=(NumberOfBus*Cost);

		Ans+=min(Sum1 , Sum2);
	}

	cout<<Ans<<endl;

	return 0 ;

}


#include <bits/stdc++.h>

#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair

using namespace std;

typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
typedef vector <ll> vll;
typedef vector <pii> vpii;
typedef vector <pll> vpll;

int main () {
  ios::sync_with_stdio(false); cin.tie(0);
  int n, m;
  cin >> n >> m;
  vi t(n);
  vi T(n);
  vi x(n);
  vi cost(n);
  for (int i = 0; i < n; i++) cin >> t[i] >> T[i] >> x[i] >> cost[i];
  auto gaaaaa = [&] (int i, int b) {
    pii b1; // (cnt, number_bus)
    pii b2; // (cnt, number_bus)
    if (m % b == 0) {
      b1 = pii(m / b, b);
      b2 = pii(0, 0);
    } else {
      int left = m % b;
      b1 = pii(m / b + 1, left);
      b2 = pii(m / b, b - left);
    }
    ll money = 1LL * cost[i] * b;
    if (t[i] + b1.first > T[i]) {
      money += 1LL * x[i] * b1.first * b1.second;
    }
    if (t[i] + b2.first > T[i]) {
      money += 1LL * x[i] * b2.first * b2.second;
    }
    return money;
  };
  ll ans = 0;
  for (int i = 0; i < n; i++) {
    ll add = LLONG_MAX;
    for (int b = 1; b <= 100; b++) {
      add = min(add, gaaaaa(i, b));
    }
    ans += add;
  }
  cout << ans << '\n';
  return (0);
}


#include <bits/stdc++.h>

#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair

using namespace std;

typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
typedef vector <ll> vll;
typedef vector <pii> vpii;
typedef vector <pll> vpll;

int main () {
  ios::sync_with_stdio(false); cin.tie(0);
  int n, m;
  cin >> n >> m;
  vi t(n);
  vi T(n);
  vi x(n);
  vi cost(n);
  for (int i = 0; i < n; i++) cin >> t[i] >> T[i] >> x[i] >> cost[i];
  auto gaaaaa = [&] (int i, int b) {
    pii b1; // (cnt, number_bus)
    pii b2; // (cnt, number_bus)
    if (m % b == 0) {
      b1 = pii(m / b, b);
      b2 = pii(0, 0);
    } else {
      int left = m % b;
      b1 = pii(m / b + 1, left);
      b2 = pii(m / b, b - left);
    }
    ll money = 1LL * cost[i] * b;
    if (t[i] + b1.first > T[i]) {
      money += 1LL * x[i] * b1.first * b1.second;
    }
    if (t[i] + b2.first > T[i]) {
      money += 1LL * x[i] * b2.first * b2.second;
    }
    return money;
  };
  ll ans = 0;
  for (int i = 0; i < n; i++) {
    ll add = gaaaaa(i, 1);
    if (t[i] < T[i]) {
      int z = m / (T[i] - t[i]);
      for (int zz: {z - 1, z, z + 1}) {
        if (zz <= 0) continue;
        add = min(add, gaaaaa(i, zz));
      }
    }
    ans += add;
  }
  cout << ans << '\n';
  return (0);
}


#include<bits/stdc++.h>
#define Z 100001
using namespace std;
long long int min(long long int a,long long int b){
    if(a<b)return a;return b;
}
int main(){
    int n,m,t,T,x,cost;
    cin>>n>>m;
    long long int ans=0,a,b;
    while(n--){
        cin>>t>>T>>x>>cost;b=-1;
        if(t<T)a=(m/(T-t)+((m%(T-t))!=0)),a*=cost,b=cost+((m+t>T?m*x:0));
        else a=cost+((m+t>T?m*x:0));
        if(b==-1)ans+=a;
        else ans +=min(b,a); //cout<<a<<" "<<b<<endl;
    }cout<<ans;
}


#include<bits/stdc++.h>
#define Z 100001
using namespace std;
long long int min(long long int a,long long int b){
    if(a<b)return a;return b;
}
int main(){
    long long int n,m,t,T,x,cost,ans=0,a,b;
    cin>>n>>m;
    while(n--){
        cin>>t>>T>>x>>cost;b=-1;
        if(t<T)a=(m/(T-t)+((m%(T-t))!=0)),a*=cost,b=cost+((m+t>T?m*x:0));
        else a=cost+((m+t>T?m*x:0));
        if(b==-1)ans+=a;
        else ans +=min(b,a); //cout<<a<<" "<<b<<endl;
    }cout<<ans;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const int maxn = 100005;
const LL INF = (LL)1e16;

int main() {
  int n, m, t, T, x, cost;
  LL res = 0;
  scanf("%d %d", &n, &m);
  while (n--) {
    scanf("%d %d %d %d", &t, &T, &x, &cost);
    LL delT = (T - t);
    LL ans = (m > delT) ? (m * 1LL * x + cost) : cost;
    if (delT < m) {
      LL bus = m / delT + (m % delT != 0) - 1;
      LL ret = min(bus * cost + (m - bus * delT + delT) * x, (bus + 1) * 1LL * cost);
      ans = min(ans, ret);
    }
    res += ans;
  }
  cout << res;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const int maxn = 100005;
const LL INF = (LL)1e16;

int main() {
  int n, m, t, T, x, cost;
  LL res = 0;
  scanf("%d %d", &n, &m);
  while (n--) {
    scanf("%d %d %d %d", &t, &T, &x, &cost);
    LL delT = (T - t);
    LL ans = (m > delT) ? (m * 1LL * x + cost) : cost;
    if (delT < m && delT > 0) {
      LL bus = m / delT + (m % delT != 0) - 1;
      LL ret = min(bus * cost + (m - bus * delT + delT) * x, (bus + 1) * 1LL * cost);
      ans = min(ans, ret);
    }
    res += ans;
  }
  cout << res;
  return 0;
}


#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<bits/stdc++.h>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<bitset>
// #include < unordered_map >
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #include "boost/algorithm/string.hpp"
#define fio ios_base::sync_with_stdio(false)
#define mod 1000000007
#define mod1 mod
#define mod2 100000009
#define li long long int
#define ll int
#define readi(x) scanf("%d",&x)
#define  reads(x)  scanf("%s", x)
#define readl(x) scanf("%I64d",&x)
#define rep(i,n) for(i=0;i<n;i++)
#define revp(i,n) for(i=(n-1);i>=0;i--)
#define myrep1(i,a,b) for(i=a;i<=b;i++)
#define myrep2(i,a,b) for(i=b;i>=a;i--)
#define pb push_back
#define mp make_pair
#define fi first
#define sec second
#define MAXN 1000000000001234000
#define MINN -1000000000000000000
#define pii pair<ll,ll>
#define pic pair<int,char>
#define N 200000
#define lgn 20
#define ddouble long double
#define minus minu
#define PI 3.1415926535
// #define INTMAX 200000000

// using namespace boost;
// #define si short int

using namespace std;
using namespace __gnu_pbds;
typedef priority_queue<pair<ll,pii> , vector<pair<ll , pii> > > max_pq;

// typedef priority_queue<pair < ll , pair < pii , ll > >  , vector<pair < ll , pair < pii , ll > >  > ,greater<pair < ll , pair < pii , ll > >  > > min_pq;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> OST;
typedef priority_queue< char , vector<char> > max_pqc;
typedef priority_queue<char, vector<char > , greater < char >  > min_pqc;

ll n , m ;
ll t[N] , T[ N ], x[N], cost[ N ];

ll low , high;
int main()
{
    ios::sync_with_stdio(false);

    cin >> n >> m;

    ll ans = 0 ;

    for ( ll i = 1; i <= n ;i ++ )
    {
        cin >> t[i] >> T[i] >> x[i] >> cost[i];
        if ( T[i] >= t[i] + m )
        {
            ans = ans + cost[i];
        }
        else if ( T[i] <= t[i] )
        {
            ans = ans + cost[i] + x[i]*m;
        }
        else
        {
            low = 0 ; high = ( m / ( T [i] - t[i] ) ) + (( m%( T[i] - t[i] ) == 0 )? 0 : 1);
            ll val = high*cost[i];
            ll slope = (t[i] - T[i])*x[i] + cost[i];
            if ( slope >=0 )
                val = min ( val , cost[i] + m*x[i] );
            else
                val = min ( val , slope*(high - 1) + m*x[i] + cost[i] );
            ans = ans + val;

        }
    }
    cout << ans << endl;

}


#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<bits/stdc++.h>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<bitset>
// #include < unordered_map >
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
// #include "boost/algorithm/string.hpp"
#define fio ios_base::sync_with_stdio(false)
#define mod 1000000007
#define mod1 mod
#define mod2 100000009
#define li long long int
#define ll li
#define readi(x) scanf("%d",&x)
#define  reads(x)  scanf("%s", x)
#define readl(x) scanf("%I64d",&x)
#define rep(i,n) for(i=0;i<n;i++)
#define revp(i,n) for(i=(n-1);i>=0;i--)
#define myrep1(i,a,b) for(i=a;i<=b;i++)
#define myrep2(i,a,b) for(i=b;i>=a;i--)
#define pb push_back
#define mp make_pair
#define fi first
#define sec second
#define MAXN 1000000000001234000
#define MINN -1000000000000000000
#define pii pair<ll,ll>
#define pic pair<int,char>
#define N 200000
#define lgn 20
#define ddouble long double
#define minus minu
#define PI 3.1415926535
// #define INTMAX 200000000

// using namespace boost;
// #define si short int

using namespace std;
using namespace __gnu_pbds;
typedef priority_queue<pair<ll,pii> , vector<pair<ll , pii> > > max_pq;

// typedef priority_queue<pair < ll , pair < pii , ll > >  , vector<pair < ll , pair < pii , ll > >  > ,greater<pair < ll , pair < pii , ll > >  > > min_pq;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> OST;
typedef priority_queue< char , vector<char> > max_pqc;
typedef priority_queue<char, vector<char > , greater < char >  > min_pqc;

ll n , m ;
ll t[N] , T[ N ], x[N], cost[ N ];

ll low , high;
int main()
{
    ios::sync_with_stdio(false);

    cin >> n >> m;

    ll ans = 0 ;

    for ( ll i = 1; i <= n ;i ++ )
    {
        cin >> t[i] >> T[i] >> x[i] >> cost[i];
        if ( T[i] >= t[i] + m )
        {
            ans = ans + cost[i];
        }
        else if ( T[i] <= t[i] )
        {
            ans = ans + cost[i] + x[i]*m;
        }
        else
        {
            low = 0 ; high = ( m / ( T [i] - t[i] ) ) + (( m%( T[i] - t[i] ) == 0 )? 0 : 1);
            ll val = high*cost[i];
            ll slope = (t[i] - T[i])*x[i] + cost[i];
            if ( slope >=0 )
                val = min ( val , cost[i] + m*x[i] );
            else
                val = min ( val , slope*(high - 1) + m*x[i] + cost[i] );
            ans = ans + val;

        }
    }
    cout << ans << endl;

}


#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")

#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 DEBUG
#ifdef DEBUG
#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
	template <typename Arg1>
	void __f(const char* name, Arg1&& arg1)
	{
		cerr << name << " = " << arg1 << 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 debug(...)
#endif

template <class Ch, class Tr, class Container>
basic_ostream <Ch, Tr> & operator << (basic_ostream <Ch, Tr> & os, Container const& x) {
    os << "{ ";
    for(auto& y : x) os << y << " ; ";
    return os << "}";
}

template <class X, class Y>
ostream & operator << (ostream & os, pair <X, Y> const& p) {
	return os << "[ " << p.first << ", " << p.second << "]" ;
}

#define FAST_IO std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long int
#define pb push_back
#define mp make_pair
#define ld long double
#define sz(a) (ll)(a).size()
#define endl "\n"

// priority_queue<ll, vector<ll>, less<ll>>pq;     // Max Heap
// priority_queue<ll, vector<ll>, greater<ll>>pq;  // Min Heap

typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
//K-th smallest
//cout << k << "kth (1 based indexing) smallest: " << *A.find_by_order(k - 1) << endl;
//NO OF ELEMENTS < X
//cout << "No of elements less than " << X << " are " << A.order_of_key(X) << endl;

const int MAXN = 1e5 + 5;
const int MAXM = 1e6 + 5;

ll n, m, t[MAXN], T[MAXN], x[MAXN], c[MAXN], b[MAXN], ans;

int main()
{
	FAST_IO;

 	cin >> n >> m;
 	for(int i=0;i<n;i++)
 	{
 		cin >> t[i] >> T[i] >> x[i] >> c[i];
 		b[i] = T[i] - t[i];
 	}
 	for(int i=0;i<n;i++)
 	{
 		if(b[i] <= 0)
 		{
 			ans += m * x[i] + c[i];
 			continue;
 		}
 		ll temp = (m + b[i] - 1) / b[i];
 		ans += min(temp * c[i], m * x[i] + c[i]);
 	}
 	cout << ans << endl;
    return 0;
}


#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")

#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 DEBUG
#ifdef DEBUG
#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
	template <typename Arg1>
	void __f(const char* name, Arg1&& arg1)
	{
		cerr << name << " = " << arg1 << 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 debug(...)
#endif

template <class Ch, class Tr, class Container>
basic_ostream <Ch, Tr> & operator << (basic_ostream <Ch, Tr> & os, Container const& x) {
    os << "{ ";
    for(auto& y : x) os << y << " ; ";
    return os << "}";
}

template <class X, class Y>
ostream & operator << (ostream & os, pair <X, Y> const& p) {
	return os << "[ " << p.first << ", " << p.second << "]" ;
}

#define FAST_IO std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long int
#define pb push_back
#define mp make_pair
#define ld long double
#define sz(a) (ll)(a).size()
#define endl "\n"

// priority_queue<ll, vector<ll>, less<ll>>pq;     // Max Heap
// priority_queue<ll, vector<ll>, greater<ll>>pq;  // Min Heap

typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
//K-th smallest
//cout << k << "kth (1 based indexing) smallest: " << *A.find_by_order(k - 1) << endl;
//NO OF ELEMENTS < X
//cout << "No of elements less than " << X << " are " << A.order_of_key(X) << endl;

const int MAXN = 1e5 + 5;
const int MAXM = 1e6 + 5;

ll n, m, t[MAXN], T[MAXN], x[MAXN], c[MAXN], b[MAXN], ans;

int main()
{
	FAST_IO;

 	cin >> n >> m;
 	for(int i=0;i<n;i++)
 	{
 		cin >> t[i] >> T[i] >> x[i] >> c[i];
 		b[i] = T[i] - t[i];
 	}
 	for(int i=0;i<n;i++)
 	{
 		if(b[i] <= 0)
 		{
 			ans += m * x[i] + c[i];
 			continue;
 		}
 		ll temp = m / b[i];
 		if(m % b[i]) temp += 1;
 		ll res = m * x[i] + c[i];
 		res = min(res, temp * c[i]);
 		if(temp >= 2) res = min(res, (temp - 1) * c[i] + (m - (temp - 2) * b[i]) * x[i]);
 		ans += res;
 	}
 	cout << ans << endl;
    return 0;
}


#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")

#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 DEBUG
#ifdef DEBUG
#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
	template <typename Arg1>
	void __f(const char* name, Arg1&& arg1)
	{
		cerr << name << " = " << arg1 << 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 debug(...)
#endif

template <class Ch, class Tr, class Container>
basic_ostream <Ch, Tr> & operator << (basic_ostream <Ch, Tr> & os, Container const& x) {
    os << "{ ";
    for(auto& y : x) os << y << " ; ";
    return os << "}";
}

template <class X, class Y>
ostream & operator << (ostream & os, pair <X, Y> const& p) {
	return os << "[ " << p.first << ", " << p.second << "]" ;
}

#define FAST_IO std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long int
#define pb push_back
#define mp make_pair
#define ld long double
#define sz(a) (ll)(a).size()
#define endl "\n"

// priority_queue<ll, vector<ll>, less<ll>>pq;     // Max Heap
// priority_queue<ll, vector<ll>, greater<ll>>pq;  // Min Heap

typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
//K-th smallest
//cout << k << "kth (1 based indexing) smallest: " << *A.find_by_order(k - 1) << endl;
//NO OF ELEMENTS < X
//cout << "No of elements less than " << X << " are " << A.order_of_key(X) << endl;

const int MAXN = 1e5 + 5;
const int MAXM = 1e6 + 5;

ll n, m, t[MAXN], T[MAXN], x[MAXN], c[MAXN], b[MAXN], ans;

int main()
{
	FAST_IO;

 	cin >> n >> m;
 	for(int i=0;i<n;i++)
 	{
 		cin >> t[i] >> T[i] >> x[i] >> c[i];
 		b[i] = T[i] - t[i];
 	}
 	for(int i=0;i<n;i++)
 	{
 		if(b[i] <= 0)
 		{
 			ans += m * x[i] + c[i];
 			continue;
 		}
 		ll temp = m / b[i];
 		if(m % b[i]) temp += 1;
 		ll res = m * x[i] + c[i];
 		res = min(res, temp * c[i]);
 		ans += res;
 	}
 	cout << ans << endl;
    return 0;
}


#include <iostream>
#include <vector>

using namespace std;

typedef long long ll;

ll mini(ll a, ll b)
{
    if (a < b)
        return a;
    return b;
}

int main()
{
    ios_base::sync_with_stdio(0);
    ll n, m;
    cin >> n >> m;
    ll odp = 0;
    for (int i = 0; i < n; ++i)
    {
        ll t, T, x, c;
        cin >> t >> T >> x >> c;
        ll ile_w_jednym = T - t;
        if (ile_w_jednym <= 0)
        {
            odp += c + m * x;
            continue;
        }
        ll ile_busow = m / ile_w_jednym;
        if (m % ile_w_jednym != 0)
            ++ile_busow;
        ll a = ile_busow * c;
        ll b;
        if (m > ile_w_jednym)
            b = c + m * x;
        else
            b = c;
        odp += mini(a, b);
    }
    cout << odp;
    return 0;
}


#include <iostream>
#include <vector>

using namespace std;

typedef long long ll;

ll mini(ll a, ll b)
{
    if (a < b)
        return a;
    return b;
}

int main()
{
    ios_base::sync_with_stdio(0);
    int n, m;
    cin >> n >> m;
    ll odp = 0;
    for (int i = 0; i < n; ++i)
    {
        ll t, T, x, c;
        cin >> t >> T >> x >> c;
        ll ile_w_jednym = T - t;
        ll ile_busow = m / ile_w_jednym;
        if (m % ile_w_jednym != 0)
            ++ile_busow;
        ll a = ile_busow * c;
        ll b;
        if (m > ile_w_jednym)
            b = c + m * x;
        else
            b = c;
        odp += mini(a, b);
    }
    cout << odp;
    return 0;
}


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

int main() {
	LL n,m,a,b,c,d,x,y,ans=0;
	scanf("%lld %lld",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%lld %lld %lld %lld",&a,&b,&c,&d);
		if(a>=b) ans += c*m+d;
		else{
			x = ceil(double(m)/double(b-a)) * d;
			y = c*m+d;
			ans += min(x,y);
		}
	}
	cout<<ans<<endl;
	return 0;
}


//Aditya Agrawal
// DTU

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <utility>
#include <iterator>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <deque>
#include <bitset>
#include <complex>
//#include <unordered_set>
//#include <unordered_map>

#define mod 1000000007
#define ima 1000000004
#define imi -1000000004
#define llma 1000000000000000004
#define llmi -1000000000000000004
#define lp(i,n) for(i=0;i<n;i++)
#define li(i,n) for(i=n-1;i>=0;i--)
#define ll long long int
#define ld long double
#define f first
#define s second
#define pa pair<ll,ll>
#define pad pair<double ,double>
#define pai pair<int,int>
#define mp make_pair
#define nn 200005
#define pi 3.1415926535898
#define inf 1e15
#define diff 1e-7
#define md 359999
#define it ::iterator
#define pb push_back
#define sync ios::sync_with_stdio(false);cout.tie(0);cin.tie(0);
#define lc(a) 2*a+1
#define rc(a) 2*a+2

using namespace std;

typedef complex<double> base;

ll x,y;

ll gcd(ll a,ll b)
{
    if(a==0)
    {
        x=0;
        y=1;
        return b;
    }

    ll gc=gcd(b%a,a);

    ll temp;
    temp=x;
    x=y-(b/a)*temp;
    y=temp;

    return gc;
}

int main()
{
    sync
    int n,m;
    int i;
    ll ans;
    cin>>n>>m;
    ans=0;
    ll t,T,x,c;
    for(i=0;i<n;i++)
    {
        cin>>t>>T>>x>>c;
        if((T-t)*x<c)
        {
            ans+=c;
            if(m>T-t)
                ans+=m*x;
        }
        else
        {
            ans+=c*ceil((double(m))/(T-t));
        }
    }
    cout<<ans<<endl;
}


//Aditya Agrawal
// DTU

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <utility>
#include <iterator>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <deque>
#include <bitset>
#include <complex>
//#include <unordered_set>
//#include <unordered_map>

#define mod 1000000007
#define ima 1000000004
#define imi -1000000004
#define llma 1000000000000000004
#define llmi -1000000000000000004
#define lp(i,n) for(i=0;i<n;i++)
#define li(i,n) for(i=n-1;i>=0;i--)
#define ll long long int
#define ld long double
#define f first
#define s second
#define pa pair<ll,ll>
#define pad pair<double ,double>
#define pai pair<int,int>
#define mp make_pair
#define nn 200005
#define pi 3.1415926535898
#define inf 1e15
#define diff 1e-7
#define md 359999
#define it ::iterator
#define pb push_back
#define sync ios::sync_with_stdio(false);cout.tie(0);cin.tie(0);
#define lc(a) 2*a+1
#define rc(a) 2*a+2

using namespace std;

typedef complex<double> base;

ll x,y;

ll gcd(ll a,ll b)
{
    if(a==0)
    {
        x=0;
        y=1;
        return b;
    }

    ll gc=gcd(b%a,a);

    ll temp;
    temp=x;
    x=y-(b/a)*temp;
    y=temp;

    return gc;
}

int main()
{
    sync
    int n,m;
    int i;
    ll ans;
    cin>>n>>m;
    ans=0;
    ll t,T,x,c;
    int temp;
    ll ma,mb;
    for(i=0;i<n;i++)
    {
        cin>>t>>T>>x>>c;

        if((T-t)<=0)
        {
            ans+=c;
            ans+=m*x;
        }
        else if((T-t)>=m)
        {
            ans+=c;
        }
        else
        {
            ma=(c+m*x);
            mb=c*(ceil(((double)m)/(T-t)));
            //cout<<ma<<" "<<mb<<endl;
            ans+=min(ma,mb);
        }
        //cout<<ans<<" ";
    }
    cout<<ans<<endl;
}


//Aditya Agrawal
// DTU

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <utility>
#include <iterator>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <deque>
#include <bitset>
#include <complex>
//#include <unordered_set>
//#include <unordered_map>

#define mod 1000000007
#define ima 1000000004
#define imi -1000000004
#define llma 1000000000000000004
#define llmi -1000000000000000004
#define lp(i,n) for(i=0;i<n;i++)
#define li(i,n) for(i=n-1;i>=0;i--)
#define ll long long int
#define ld long double
#define f first
#define s second
#define pa pair<ll,ll>
#define pad pair<double ,double>
#define pai pair<int,int>
#define mp make_pair
#define nn 200005
#define pi 3.1415926535898
#define inf 1e15
#define diff 1e-7
#define md 359999
#define it ::iterator
#define pb push_back
#define sync ios::sync_with_stdio(false);cout.tie(0);cin.tie(0);
#define lc(a) 2*a+1
#define rc(a) 2*a+2

using namespace std;

typedef complex<double> base;

ll x,y;

ll gcd(ll a,ll b)
{
    if(a==0)
    {
        x=0;
        y=1;
        return b;
    }

    ll gc=gcd(b%a,a);

    ll temp;
    temp=x;
    x=y-(b/a)*temp;
    y=temp;

    return gc;
}

int main()
{
    sync
    int n,m;
    int i;
    ll ans;
    cin>>n>>m;
    ans=0;
    ll t,T,x,c;
    int temp;
    for(i=0;i<n;i++)
    {
        cin>>t>>T>>x>>c;
        if((T-t)*x<c)
        {
            ans+=c;
            if(m>T-t)
                ans+=m*x;
        }
        else
        {
            if(m%(T-t)==0)
                temp=m/(T-t);
            else
                temp=m/(T-t) +1;
            ans+=c*temp;
        }
    }
    cout<<ans<<endl;
}


//Aditya Agrawal
// DTU

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <utility>
#include <iterator>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <deque>
#include <bitset>
#include <complex>
//#include <unordered_set>
//#include <unordered_map>

#define mod 1000000007
#define ima 1000000004
#define imi -1000000004
#define llma 1000000000000000004
#define llmi -1000000000000000004
#define lp(i,n) for(i=0;i<n;i++)
#define li(i,n) for(i=n-1;i>=0;i--)
#define ll long long int
#define ld long double
#define f first
#define s second
#define pa pair<ll,ll>
#define pad pair<double ,double>
#define pai pair<int,int>
#define mp make_pair
#define nn 200005
#define pi 3.1415926535898
#define inf 1e15
#define diff 1e-7
#define md 359999
#define it ::iterator
#define pb push_back
#define sync ios::sync_with_stdio(false);cout.tie(0);cin.tie(0);
#define lc(a) 2*a+1
#define rc(a) 2*a+2

using namespace std;

typedef complex<double> base;

ll x,y;

ll gcd(ll a,ll b)
{
    if(a==0)
    {
        x=0;
        y=1;
        return b;
    }

    ll gc=gcd(b%a,a);

    ll temp;
    temp=x;
    x=y-(b/a)*temp;
    y=temp;

    return gc;
}

int main()
{
    sync
    int n,m;
    int i;
    ll ans;
    cin>>n>>m;
    ans=0;
    ll t,T,x,c;
    for(i=0;i<n;i++)
    {
        cin>>t>>T>>x>>c;
        if((T-t)*x<=c)
        {
            ans+=c;
            if(m>T-t)
                ans+=m*x;
        }
        else
        {
            ans+=c*ceil((double(m))/(T-t));
        }
    }
    cout<<ans<<endl;
}


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

#define int long long

int N, M;

signed main(){
  ios::sync_with_stdio( 0 );
  cin >> N >> M;
  int ans = 0;
  for( int i = 0; i < N; ++i ){
    int t, T, x, cost; cin >> t >> T >> x >> cost;
    if( t + M <= T ) ans += cost;
    else if( t >= T ) ans += cost + x * M;
    else ans += min( cost + x * M, cost * ( ( M + T - t - 1 ) / ( T - t ) ) );
  }
  cout << ans << endl;
  return 0;
}


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

#define int long long

int N, M;

signed main(){
  ios::sync_with_stdio( 0 );
  cin >> N >> M;
  int ans = 0;
  for( int i = 0; i < N; ++i ){
    int t, T, x, cost; cin >> t >> T >> x >> cost;
    if( t + M <= T ) ans += cost;
    else if( t > T ) ans += cost + x * M;
    else ans += min( cost + x * M, cost * ( ( M + T - t - 1 ) / ( T - t ) ) );
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstring>
#include <cassert>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <bitset>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using pll = pair<ll, ll>;
#ifdef XVENOM
	#define errp(...) fprintf(stderr, __VA_ARGS__)
	#define dbg(...) errp("[%s]: ", #__VA_ARGS__), dbg_str(__VA_ARGS__)
#else
	#define errp(...)
	#define dbg(...)
#endif
template <typename U, typename V> string to_string (pair<U, V>);
string to_string (string& e) { return "\"" + e + "\""; }
string to_string (char e) { return "\'" + string(1, e) + "\'"; }
string to_string (bool e) { return e ? "true" : "false"; }
template <typename T> string to_string (T e) {
	string s = "[ ";
	for (auto& x : e) s += to_string(x) + " ";
	return s + "]";
}
template <typename U, typename V> string to_string (pair<U, V> e) {
	return "(" + to_string(e.first) + ", " + to_string(e.second) + ")";
}
void dbg_str () { errp(" \n"); }
template <typename U, typename... V> void dbg_str (U u, V... v) {
 	errp(" %s", to_string(u).c_str()); dbg_str(v...);
}
/* --- */
ll n, m, t, T, x, cost;

ll solve() {
	ll k = T - t;
	if (k <= 0) return cost + m * x;
	ll bc = (m - 1) / k + 1;
	if (bc == 1) return cost;
	ll res = bc * cost;
	if (cost - k * x < 0)
		res = min(res, (bc - 1) * (cost - k * x) + (m + k) * x);
	else
		res = min(res, (cost - k * x) + (m + k) * x);
	return res;
}

int main() {
	scanf("%lld%lld", &n, &m);
	ll ans = 0;
	for (int i = 0; i < n; i++) {
		scanf("%lld%lld%lld%lld", &t, &T, &x, &cost);
		ans += solve();
	}
	printf("%lld\n", ans);
}


#include<bits/stdc++.h>
using   namespace     std;
#define flash         ios_base::sync_with_stdio(false);cin.tie(0);
#define ff            first
#define ss            second
#define m_p           make_pair
typedef pair<int,int> pii;
typedef pair<int,pii> ppi;
typedef long long int ll;
int main ()
{
    int n,m;
    cin>>n>>m;
    ll t,T,x,cost;
    ll ans=0;
    for(int i=0;i<n;i++)
    {
        cin>>t>>T>>x>>cost;
        ll nm = ceil(m*1./(T-t)*1.);
        ll com = cost + m * x;
        ll n_com = nm * cost;
        if(n_com<com) ans+=n_com;
        else ans+=com;
        //cout<<ans<<endl;
    }
    cout<<ans;
    return 0;
}


#include<bits/stdc++.h>
using   namespace     std;
#define flash         ios_base::sync_with_stdio(false);cin.tie(0);
#define ff            first
#define ss            second
#define m_p           make_pair
typedef pair<int,int> pii;
typedef pair<int,pii> ppi;
typedef long long int ll;
int main ()
{
    int n,m;
    cin>>n>>m;
    ll t,T,x,cost;
    ll ans=0;
    for(int i=0;i<n;i++)
    {
        cin>>t>>T>>x>>cost;
        ll nm = ceil(m*1./(T-t)*1.);
        ll com = cost + m * x;
        ll n_com = nm * cost;
        if(n_com<com && n_com>0) ans+=n_com;
        else ans+=com;
        //cout<<ans<<endl;
    }
    cout<<ans;
    return 0;
}


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

typedef long long ll;
typedef pair<ll, ll> pll;

int N, S, M;
struct Info {
    int s, a, b;
};
vector<Info> info;

bool cmp1(Info a, Info b) {
    return a.a - a.b < b.a - b.b;
}
bool cmp2(Info a, Info b) {
    return a.b - a.a < b.b - b.a;
}

ll sum = 0, cnt1 = 0, cnt2 = 0, ans = 0;

int main() {
    scanf("%d %d", &N, &S);

    info.resize(N);

    for(int i = 0; i < N; i++) {
        scanf("%d %d %d", &info[i].s, &info[i].a, &info[i].b);
        sum += info[i].s;
    }

    M = (sum + S - 1) / S;

    for(int i = 0; i < N; i++) {
        if(info[i].a > info[i].b) cnt1 += info[i].s;
        if(info[i].a < info[i].b) cnt2 += info[i].s;
    }

    if(M >= (cnt1 + S - 1) / S + (cnt2 + S - 1) / S) {
        for(int i = 0; i < N; i++) {
            ans += 1LL * info[i].s * max(info[i].a, info[i].b);
        }
        cout << ans;
        return 0;
    }

    if(1) {
        sort(info.begin(), info.end(), cmp1);

        ll cost = 0;
        for(int i = 0; i < N; i++) {
            cost += 1LL * info[i].b * info[i].s;
        }
        ll over = ((cnt1 + S - 1) / S - 1) * S;

        for(int i = N - 1; i >= 0; i--) {
            ll tmp = min(over, (ll)info[i].s);
            over -= tmp;
            cost += 1LL * (info[i].a - info[i].b) * tmp;
            if(over == 0) break;
        }

        ans = max(ans, cost);
    }
    if(2) {
        sort(info.begin(), info.end(), cmp2);

        ll cost = 0;
        for(int i = 0; i < N; i++) {
            cost += 1LL * info[i].a * info[i].s;
        }
        ll over = ((cnt2 + S - 1) / S - 1) * S;

        for(int i = N - 1; i >= 0; i--) {
            ll tmp = min(over, (ll)info[i].s);
            over -= tmp;
            cost += 1LL * (info[i].b - info[i].a) * tmp;
            if(over == 0) break;
        }

        ans = max(ans, cost);
    }

    cout << ans;
}


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

typedef long long ll;
typedef pair<ll, ll> pll;

int N, S;
ll M;
struct Info {
    int s, a, b;
};
vector<Info> info;

bool cmp1(Info a, Info b) {
    return a.a - a.b < b.a - b.b;
}
bool cmp2(Info a, Info b) {
    return a.b - a.a < b.b - b.a;
}

ll sum = 0, cnt1 = 0, cnt2 = 0, ans = 0;

int main() {
    scanf("%d %d", &N, &S);

    info.resize(N);

    for(int i = 0; i < N; i++) {
        scanf("%d %d %d", &info[i].s, &info[i].a, &info[i].b);
        sum += info[i].s;
    }

    M = (sum + S - 1) / S;

    for(int i = 0; i < N; i++) {
        if(info[i].a > info[i].b) cnt1 += info[i].s;
        if(info[i].a < info[i].b) cnt2 += info[i].s;
    }

    if(M >= (cnt1 + S - 1) / S + (cnt2 + S - 1) / S) {
        for(int i = 0; i < N; i++) {
            ans += 1LL * info[i].s * max(info[i].a, info[i].b);
        }
        cout << ans;
        return 0;
    }

    if(1) {
        sort(info.begin(), info.end(), cmp1);

        ll cost = 0;
        for(int i = 0; i < N; i++) {
            cost += 1LL * info[i].b * info[i].s;
        }
        ll over = ((cnt1 + S - 1) / S - 1) * S;

        for(int i = N - 1; i >= 0; i--) {
            ll tmp = min(over, (ll)info[i].s);
            over -= tmp;
            cost += 1LL * (info[i].a - info[i].b) * tmp;
            if(over == 0) break;
        }

        ans = max(ans, cost);
    }
    if(2) {
        sort(info.begin(), info.end(), cmp2);

        ll cost = 0;
        for(int i = 0; i < N; i++) {
            cost += 1LL * info[i].a * info[i].s;
        }
        ll over = ((cnt2 + S - 1) / S - 1) * S;

        for(int i = N - 1; i >= 0; i--) {
            ll tmp = min(over, (ll)info[i].s);
            over -= tmp;
            cost += 1LL * (info[i].b - info[i].a) * tmp;
            if(over == 0) break;
        }

        ans = max(ans, cost);
    }

    cout << ans;
}


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

typedef long long ll;
typedef pair<ll, ll> pll;

int N, S, M;
struct Info {
    int s, a, b;
};
vector<Info> info;

ll sum = 0;
ll cost = 0;
ll ans;

priority_queue<pll> pq;
ll a, b;

int main() {
    scanf("%d %d", &N, &S);

    info.resize(N);

    for(int i = 0; i < N; i++) {
        scanf("%d %d %d", &info[i].s, &info[i].a, &info[i].b);
        sum += info[i].s;
    }

    M = (sum + S - 1) / S;

    for(int i = 0; i < N; i++) {
        cost += 1LL * info[i].a * info[i].s;
        pq.push(pll(info[i].b - info[i].a, info[i].s));
    }
    a = sum;
    b = 0;
    ans = cost;

    for(int i = 1; i <= M; i++) {
        ll L = max(0LL, a - 1LL * (M - i) * S);
        ll R = 1LL * i * S - b;

        while(1) {
            if(L == 0) break;
            pll t = pq.top(); pq.pop();

            ll tmp = min(L, t.second);
            cost += t.first * tmp;
            L -= tmp;
            R -= tmp;
            t.second -= tmp;
            a -= tmp;
            b += tmp;

            if(t.second) pq.push(t);
        }
        while(1) {
            if(R == 0 || pq.empty()) break;
            pll t = pq.top();
            if(t.first <= 0) break;
            pq.pop();

            ll tmp = min(R, t.second);
            cost += t.first * tmp;
            R -= tmp;
            t.second -= tmp;
            a -= tmp;
            b += tmp;

            if(t.second) pq.push(t);
        }

        ans = max(ans, cost);
    }

    cout << ans;
}


#include <bits/stdc++.h>
using namespace std;
const int MaxN = 100003;
typedef long long LL;
int n,s;LL sum,need;
struct People{int a,b,c;}a[MaxN];

LL solve(LL sa) {
    static People a[MaxN];
    memcpy(a,::a,sizeof a);
    LL ret=0;
    LL sb=need-sa;
    sa*=s,sb*=s;
    for (int i=1;i<=n && sa>0;++i) if (a[i].a-a[i].b>=0) {
        LL eat=min(sa,(LL)a[i].c);
        ret+=eat*a[i].a;
        sa-=eat,a[i].c-=eat;
    }
    for (int i=n;i>=1 && sb>0;--i) if (a[i].a-a[i].b<=0) {
        LL eat=min(sb,(LL)a[i].c);
        ret+=eat*a[i].b;
        sb-=eat,a[i].c-=eat;
    }
    if (sa) {
        for (int i=1;i<=n && sa>0;++i) {
            LL eat=min(sa,(LL)a[i].c);
            ret+=eat*a[i].a;
            sa-=eat,a[i].c-=eat;
        }
    }
    if (sb) {
        for (int i=n;i>=1 && sb>0;--i) {
            LL eat=min(sb,(LL)a[i].c);
            ret+=eat*a[i].b;
            sb-=eat,a[i].c-=eat;
        }
    }
    return ret;
}

inline void check(LL& mx,LL& ans,LL x) {
    if (x<0 || x>need) return;
    LL t=solve(x);
    if (t>mx) mx=t,ans=x;
}

int main() {
    scanf("%d%d",&n,&s);
    for (int i=1;i<=n;++i) {
        int aa,bb,cc;
        scanf("%d%d%d",&cc,&aa,&bb);
        a[i]={aa,bb,cc};
        sum+=cc;
    }
    sort(a+1,a+n+1,[](const People& a,const People& b){return a.a-a.b>b.a-b.b;});
    need=(sum+s-1)/s;
    /*
    LL l=0,r=need;
    while (l<r) {
        if (r-l<=5) {
            LL mx=solve(l),ans=l;
            for (LL i=l+1;i<=r;++i) {
                LL t=solve(i);
                if (t>mx) mx=t,ans=i;
            }
            l=r=ans;
            break;
        }
        LL mid=(l+r+1)/2,midmid=(mid+r)/2;
        if (solve(mid)<=solve(midmid)) l=mid;
        else r=midmid;
    }
    printf("%lld\n",solve(l));
    */
    LL mx=solve(0),ans=0;
    LL sa=0,sb=0,sc=0;
    for (int i=1;i<=n;++i) if (a[i].a-a[i].b>0) sa+=a[i].c;else if (a[i].a-a[i].b==0) sb+=a[i].c;else sc+=a[i].c;
    check(mx,ans,sa/s);check(mx,ans,(sa+s-1)/s);
    check(mx,ans,(sa+sc)/s);check(mx,ans,(sa+sc+s-1)/s);
    check(mx,ans,need-sb/s);check(mx,ans,need-(sb+s-1)/s);
    check(mx,ans,need-(sb+sc)/s);check(mx,ans,need-(sb+sc+s-1)/s);
    printf("%lld\n",mx);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int MaxN = 100003;
typedef long long LL;
int n,s;LL sum,need;
struct People{int a,b,c;}a[MaxN];

LL solve(LL sa) {
    static People a[MaxN];
    memcpy(a,::a,sizeof a);
    LL ret=0;
    LL sb=need-sa;
    sa*=s,sb*=s;
    int i=1;
    while (i<=n && sa>0) {
        LL eat=min(sa,LL(a[i].c));
        ret+=eat*a[i].a;
        sa-=eat;a[i].c-=eat;
        if (a[i].c==0) i++;
    }
    while (i<=n && sb>0) {
        LL eat=min(sb,LL(a[i].c));
        ret+=eat*a[i].b;
        sb-=eat;a[i].c-=eat;
        if (a[i].c==0) i++;
    }
    return ret;
}

int main() {
    scanf("%d%d",&n,&s);
    for (int i=1;i<=n;++i) {
        int aa,bb,cc;
        scanf("%d%d%d",&cc,&aa,&bb);
        a[i]={aa,bb,cc};
        sum+=cc;
    }
    sort(a+1,a+n+1,[](const People& a,const People& b){return a.a-a.b>b.a-b.b;});
    need=(sum+s-1)/s;
    LL l=0,r=need;
    while (l<r) {
        if (r-l<=5) {
            LL mx=solve(l),ans=l;
            for (LL i=l+1;i<=r;++i) {
                LL t=solve(i);
                if (t>mx) mx=t,ans=i;
            }
            l=r=ans;
            break;
        }
        LL mid=(l+r+1)/2,midmid=(mid+r)/2;
        if (solve(mid)<=solve(midmid)) l=mid;
        else r=midmid;
    }
    printf("%lld\n",solve(l));
}


#include <bits/stdc++.h>
using namespace std;
const int MaxN = 100003;
typedef long long LL;
int n,s;LL sum,need;
struct People{int a,b,c;}a[MaxN];

LL solve(LL sa) {
    static People a[MaxN];
    memcpy(a,::a,sizeof a);
    LL ret=0;
    LL sb=need-sa;
    sa*=s,sb*=s;
    int i=1;
    while (i<=n && sa>0) {
        LL eat=min(sa,LL(a[i].c));
        ret+=eat*a[i].a;
        sa-=eat;a[i].c-=eat;
        if (a[i].c==0) i++;
    }
    while (i<=n && sb>0) {
        LL eat=min(sb,LL(a[i].c));
        ret+=eat*a[i].b;
        sb-=eat;a[i].c-=eat;
        if (a[i].c==0) i++;
    }
    return ret;
}

inline void check(LL& mx,LL& ans,LL x) {
    if (x<0 || x>need) return;
    LL t=solve(x);
    if (t>mx) mx=t,ans=x;
}

int main() {
    scanf("%d%d",&n,&s);
    for (int i=1;i<=n;++i) {
        int aa,bb,cc;
        scanf("%d%d%d",&cc,&aa,&bb);
        a[i]={aa,bb,cc};
        sum+=cc;
    }
    sort(a+1,a+n+1,[](const People& a,const People& b){return a.a-a.b>b.a-b.b;});
    need=(sum+s-1)/s;
    /*
    LL l=0,r=need;
    while (l<r) {
        if (r-l<=5) {
            LL mx=solve(l),ans=l;
            for (LL i=l+1;i<=r;++i) {
                LL t=solve(i);
                if (t>mx) mx=t,ans=i;
            }
            l=r=ans;
            break;
        }
        LL mid=(l+r+1)/2,midmid=(mid+r)/2;
        if (solve(mid)<=solve(midmid)) l=mid;
        else r=midmid;
    }
    printf("%lld\n",solve(l));
    */
    LL mx=solve(0),ans=0;
    LL sa=0,sb=0,sc=0;
    for (int i=1;i<=n;++i) if (a[i].a-a[i].b>0) sa+=a[i].c;else if (a[i].a-a[i].b==0) sb+=a[i].c;else sc+=a[i].c;
    check(mx,ans,sa/s);check(mx,ans,(sa+s-1)/s);
    check(mx,ans,(sa+sc)/s);check(mx,ans,(sa+sc+s-1)/s);
    check(mx,ans,need-sb/s);check(mx,ans,need-(sb+s-1)/s);
    check(mx,ans,need-(sb+sc)/s);check(mx,ans,need-(sb+sc+s-1)/s);
    printf("%lld\n",mx);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int MaxN = 100003;
typedef long long LL;
int n,s;LL sum,need;
struct People{int a,b,c;}a[MaxN];

LL solve(LL sa) {
    static People a[MaxN];
    memcpy(a,::a,sizeof a);
    LL ret=0;
    LL sb=need-sa;
    sa*=s,sb*=s;
    int i=1;
    while (i<=n && sa>0) {
        LL eat=min(sa,LL(a[i].c));
        ret+=eat*a[i].a;
        sa-=eat;a[i].c-=eat;
        if (a[i].c==0) i++;
    }
    while (i<=n && sb>0) {
        LL eat=min(sb,LL(a[i].c));
        ret+=eat*a[i].b;
        sb-=eat;a[i].c-=eat;
        if (a[i].c==0) i++;
    }
    return ret;
}

int main() {
    scanf("%d%d",&n,&s);
    for (int i=1;i<=n;++i) {
        int aa,bb,cc;
        scanf("%d%d%d",&cc,&aa,&bb);
        a[i]={aa,bb,cc};
        sum+=cc;
    }
    sort(a+1,a+n+1,[](const People& a,const People& b){return a.a-a.b>b.a-b.b;});
    need=(sum+s-1)/s;
    LL l=0,r=need;
    while (l<r) {
        if (r-l<=5) {
            LL mx=solve(l),ans=l;
            for (LL i=l+1;i<=r;++i) {
                LL t=solve(i);
                if (t>mx) mx=t,ans=i;
            }
            l=r=ans;
        }
        LL mid=(l+r)/2,midmid=(mid+r)/2;
        if (solve(mid)<solve(midmid)) l=mid;
        else r=midmid;
    }
    printf("%lld\n",solve(l));
}


#include <bits/stdc++.h>
#include <ext/hash_map>
#include <ext/numeric>

using namespace std;
using namespace __gnu_cxx;

#define REP(i,n) for( (i)=0 ; (i)<(n) ; (i)++ )
#define rep(i,x,n) for( (i)=(x) ; (i)<(n) ; (i)++ )
#define REV(i,n) for( (i)=(n) ; (i)>=0 ; (i)-- )
#define FORIT(it,x) for( (it)=(x).begin() ; (it)!=(x).end() ; (it)++ )
#define foreach(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
#define rforeach(it,c) for(__typeof((c).rbegin()) it=(c).rbegin();it!=(c).rend();++it)
#define foreach2d(i, j, v) foreach(i,v) foreach(j,*i)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define SZ(x) ((int)(x).size())
#define MMS(x,n) memset(x,n,sizeof(x))
#define mms(x,n,s) memset(x,n,sizeof(x)*s)
#define pb push_back
#define mp make_pair
#define NX next_permutation
#define UN(x) sort(all(x)),x.erase(unique(all(x)),x.end())
#define CV(x,n) count(all(x),(n))
#define FIND(x,n) find(all(x),(n))-(x).begin()
#define ACC(x) accumulate(all(x),0)
#define PPC(x) __builtin_popcountll(x)
#define LZ(x) __builtin_clz(x)
#define TZ(x) __builtin_ctz(x)
#define mxe(x) *max_element(all(x))
#define mne(x) *min_element(all(x))
#define low(x,i) lower_bound(all(x),i)
#define upp(x,i) upper_bound(all(x),i)
#define NXPOW2(x) (1ll << ((int)log2(x)+1))
#define PR(x) cout << #x << " = " << (x) << endl ;

typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef pair<int, int> pii;

const int OO = (int) 2e9;
const double eps = 1e-9;

const int N = 100005;

int n, k;
ll s[N], a[N], b[N];
vector<pii> ga, gb;
ll tot, cnta, cntb, suma, sumb;

int main() {
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
#ifndef ONLINE_JUDGE
//	freopen("in.txt", "rt", stdin);
//	freopen("out.txt", "wt", stdout);
#endif
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		cin >> s[i] >> a[i] >> b[i];
		tot += s[i];
		if (a[i] > b[i]) {
			ga.pb(mp(a[i] - b[i], i));
			cnta += s[i];
			suma += s[i] * a[i];
		} else {
			gb.pb(mp(b[i] - a[i], i));
			cntb += s[i];
			sumb += s[i] * b[i];
		}
	}
	ll res = suma + sumb;
	if ((cnta + k - 1) / k + (cntb + k - 1) / k == (tot + k - 1) / k) {
		cout << res << endl;
		return 0;
	}
	sort(all(ga));
	sort(all(gb));
	cnta %= k;
	cntb %= k;
	ll da = 0, db = 0;
	for (auto it : ga) {
		ll cur = min(cnta, s[it.second]);
		da += cur * it.first;
		cnta -= cur;
		if (cnta == 0)
			break;
	}
	for (auto it : gb) {
		ll cur = min(cntb, s[it.second]);
		db += cur * it.first;
		cntb -= cur;
		if (cntb == 0)
			break;
	}
	res -= min(da, db);
	cout << res << endl;
	return 0;
}


#include <bits/stdc++.h>
#include <ext/hash_map>
#include <ext/numeric>

using namespace std;
using namespace __gnu_cxx;

#define REP(i,n) for( (i)=0 ; (i)<(n) ; (i)++ )
#define rep(i,x,n) for( (i)=(x) ; (i)<(n) ; (i)++ )
#define REV(i,n) for( (i)=(n) ; (i)>=0 ; (i)-- )
#define FORIT(it,x) for( (it)=(x).begin() ; (it)!=(x).end() ; (it)++ )
#define foreach(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
#define rforeach(it,c) for(__typeof((c).rbegin()) it=(c).rbegin();it!=(c).rend();++it)
#define foreach2d(i, j, v) foreach(i,v) foreach(j,*i)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define SZ(x) ((int)(x).size())
#define MMS(x,n) memset(x,n,sizeof(x))
#define mms(x,n,s) memset(x,n,sizeof(x)*s)
#define pb push_back
#define mp make_pair
#define NX next_permutation
#define UN(x) sort(all(x)),x.erase(unique(all(x)),x.end())
#define CV(x,n) count(all(x),(n))
#define FIND(x,n) find(all(x),(n))-(x).begin()
#define ACC(x) accumulate(all(x),0)
#define PPC(x) __builtin_popcountll(x)
#define LZ(x) __builtin_clz(x)
#define TZ(x) __builtin_ctz(x)
#define mxe(x) *max_element(all(x))
#define mne(x) *min_element(all(x))
#define low(x,i) lower_bound(all(x),i)
#define upp(x,i) upper_bound(all(x),i)
#define NXPOW2(x) (1ll << ((int)log2(x)+1))
#define PR(x) cout << #x << " = " << (x) << endl ;

typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef pair<int, int> pii;

const int OO = (int) 2e9;
const double eps = 1e-9;

const int N = 100005;

int n, k;
int s[N], a[N], b[N];
vector<int> ga, gb, ge;
ll tot, cnt, suma, sumb, sume;
vector<pair<int, pair<int, int> > > g;

struct cmp {
	bool operator()(const pair<int, pii> &x, const pair<int, pii> &y) const {
		if (x.second.first > x.second.second) {
			if (y.second.first > y.second.second) {
				if (x.second.first == y.second.first)
					return x.second.second < y.second.second;
				return x.second.first > y.second.first;
			} else {
				return 1;
			}
		} else if (x.second.first == x.second.second) {
			if (y.second.first > y.second.second) {
				return 0;
			} else {
				return 1;
			}
		}
		if (y.second.first >= y.second.second) {
			return 0;
		}
		return (x.second.second < y.second.second);
	}
};

ll calc(ll ca) {
	ll cb = cnt - ca;
	ca *= k;
	cb *= k;
	ll res = 0;
	for (int i = 0; i < n; i++) {
		ll cur = min(ca, g[i].first * 1LL);
		res += cur * g[i].second.first;
		ca -= cur;
		if (g[i].first > cur) {
			cur = g[i].first - cur;
			res += cur * g[i].second.second;
			cb -= cur;
		}
	}
	return res;
}

ll calc2(ll cb) {
	ll ca = cnt - cb;
	cb *= k;
	ca *= k;
	ll res = 0;
	for (int i = n - 1; i >= 0; i--) {
		ll cur = min(cb, g[i].first * 1LL);
		res += cur * g[i].second.second;
		cb -= cur;
		if (g[i].first > cur) {
			cur = g[i].first - cur;
			res += cur * g[i].second.first;
			ca -= cur;
		}
	}
	return res;
}

int main() {
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
#ifndef ONLINE_JUDGE
//	freopen("in.txt", "rt", stdin);
//	freopen("out.txt", "wt", stdout);
#endif
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		cin >> s[i] >> a[i] >> b[i];
		g.pb(mp(s[i], mp(a[i], b[i])));
		tot += s[i];
		if (a[i] > b[i]) {
			ga.pb(i);
			suma += s[i];
		} else if (a[i] < b[i]) {
			gb.pb(i);
			sumb += s[i];
		} else {
			ge.pb(i);
			sume += s[i];
		}
	}
	sort(all(g), cmp());
	cnt = tot / k + bool(tot % k);
	ll st = 0, en = cnt;
	while (st < en) {
		ll mid = st + (en - st) / 2;
		if (calc(mid) < calc(mid + 1))
			st = mid + 1;
		else
			en = mid;
	}
	ll res = calc(st);
	st = 0, en = cnt;
	while (st < en) {
		ll mid = st + (en - st) / 2;
		if (calc2(mid) < calc2(mid + 1))
			st = mid + 1;
		else
			en = mid;
	}
	res = max(res, calc2(st));
	int lim = min(n, 10000000 / n);
	for (int i = 0; i <= lim; i++) {
		res = max(res, calc(i));
		res = max(res, calc2(i));
	}
	cout << res << endl;
	return 0;
}


// Herping Derping

#include <bits/stdc++.h>
#include <ext/hash_map>
#include <ext/numeric>

using namespace std;
using namespace __gnu_cxx;

#define REP(i,n) for( (i)=0 ; (i)<(n) ; (i)++ )
#define rep(i,x,n) for( (i)=(x) ; (i)<(n) ; (i)++ )
#define REV(i,n) for( (i)=(n) ; (i)>=0 ; (i)-- )
#define FORIT(it,x) for( (it)=(x).begin() ; (it)!=(x).end() ; (it)++ )
#define foreach(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
#define rforeach(it,c) for(__typeof((c).rbegin()) it=(c).rbegin();it!=(c).rend();++it)
#define foreach2d(i, j, v) foreach(i,v) foreach(j,*i)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define SZ(x) ((int)(x).size())
#define MMS(x,n) memset(x,n,sizeof(x))
#define mms(x,n,s) memset(x,n,sizeof(x)*s)
#define pb push_back
#define mp make_pair
#define NX next_permutation
#define UN(x) sort(all(x)),x.erase(unique(all(x)),x.end())
#define CV(x,n) count(all(x),(n))
#define FIND(x,n) find(all(x),(n))-(x).begin()
#define ACC(x) accumulate(all(x),0)
#define PPC(x) __builtin_popcountll(x)
#define LZ(x) __builtin_clz(x)
#define TZ(x) __builtin_ctz(x)
#define mxe(x) *max_element(all(x))
#define mne(x) *min_element(all(x))
#define low(x,i) lower_bound(all(x),i)
#define upp(x,i) upper_bound(all(x),i)
#define NXPOW2(x) (1ll << ((int)log2(x)+1))
#define PR(x) cout << #x << " = " << (x) << endl ;

typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef pair<int, int> pii;

const int OO = (int) 2e9;
const double eps = 1e-9;

const int N = 100005;

int n, k;
int s[N], a[N], b[N];
vector<int> ga, gb, ge;
ll tot, cnt, suma, sumb, sume;
vector<pair<int, pair<int, int> > > g;

struct cmp {
	bool operator()(const pair<int, pii> &x, const pair<int, pii> &y) const {
		if (x.second.first > x.second.second) {
			if (y.second.first > y.second.second) {
				if (x.second.first == y.second.first)
					return x.second.second < y.second.second;
				return x.second.first > y.second.first;
			} else {
				return 1;
			}
		} else if (x.second.first == x.second.second) {
			if (y.second.first > y.second.second) {
				return 0;
			} else {
				return 1;
			}
		}
		if (y.second.first >= y.second.second) {
			return 0;
		}
		return (x.second.second < y.second.second);
	}
};

ll calc(ll ca) {
	ll cb = cnt - ca;
	ca *= k;
	cb *= k;
	ll res = 0;
	for (int i = 0; i < n; i++) {
		ll cur = min(ca, g[i].first * 1LL);
		res += cur * g[i].second.first;
		ca -= cur;
		if (g[i].first > cur) {
			cur = g[i].first - cur;
			res += cur * g[i].second.second;
			cb -= cur;
		}
	}
	return res;
}

int main() {
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
#ifndef ONLINE_JUDGE
//	freopen("in.txt", "rt", stdin);
//	freopen("out.txt", "wt", stdout);
#endif
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		cin >> s[i] >> a[i] >> b[i];
		g.pb(mp(s[i], mp(a[i], b[i])));
		tot += s[i];
		if (a[i] > b[i]) {
			ga.pb(i);
			suma += s[i];
		} else if (a[i] < b[i]) {
			gb.pb(i);
			sumb += s[i];
		} else {
			ge.pb(i);
			sume += s[i];
		}
	}
	sort(all(g), cmp());
	cnt = tot / k + bool(tot % k);
	ll st = 0, en = cnt;
	while (st < en) {
		ll mid = st + (en - st) / 2;
		if (calc(mid) < calc(mid + 1))
			st = mid + 1;
		else
			en = mid;
	}
	cout << calc(st) << endl;
	return 0;
}


// have no idea what i'm doing

#include <bits/stdc++.h>
#include <ext/hash_map>
#include <ext/numeric>

using namespace std;
using namespace __gnu_cxx;

#define REP(i,n) for( (i)=0 ; (i)<(n) ; (i)++ )
#define rep(i,x,n) for( (i)=(x) ; (i)<(n) ; (i)++ )
#define REV(i,n) for( (i)=(n) ; (i)>=0 ; (i)-- )
#define FORIT(it,x) for( (it)=(x).begin() ; (it)!=(x).end() ; (it)++ )
#define foreach(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
#define rforeach(it,c) for(__typeof((c).rbegin()) it=(c).rbegin();it!=(c).rend();++it)
#define foreach2d(i, j, v) foreach(i,v) foreach(j,*i)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define SZ(x) ((int)(x).size())
#define MMS(x,n) memset(x,n,sizeof(x))
#define mms(x,n,s) memset(x,n,sizeof(x)*s)
#define pb push_back
#define mp make_pair
#define NX next_permutation
#define UN(x) sort(all(x)),x.erase(unique(all(x)),x.end())
#define CV(x,n) count(all(x),(n))
#define FIND(x,n) find(all(x),(n))-(x).begin()
#define ACC(x) accumulate(all(x),0)
#define PPC(x) __builtin_popcountll(x)
#define LZ(x) __builtin_clz(x)
#define TZ(x) __builtin_ctz(x)
#define mxe(x) *max_element(all(x))
#define mne(x) *min_element(all(x))
#define low(x,i) lower_bound(all(x),i)
#define upp(x,i) upper_bound(all(x),i)
#define NXPOW2(x) (1ll << ((int)log2(x)+1))
#define PR(x) cout << #x << " = " << (x) << endl ;

typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef pair<int, int> pii;

const int OO = (int) 2e9;
const double eps = 1e-9;

const int N = 100005;

int n, k;
int s[N], a[N], b[N];
vector<int> ga, gb, ge;
ll tot, cnt, suma, sumb, sume;
vector<pair<int, pair<int, int> > > g;

struct cmp {
	bool operator()(const pair<int, pii> &x, const pair<int, pii> &y) const {
		if (x.second.first > x.second.second) {
			if (y.second.first > y.second.second) {
				if (x.second.first == y.second.first)
					return x.second.second < y.second.second;
				return x.second.first > y.second.first;
			} else {
				return 1;
			}
		} else if (x.second.first == x.second.second) {
			if (y.second.first > y.second.second) {
				return 0;
			} else {
				return 1;
			}
		}
		if (y.second.first >= y.second.second) {
			return 0;
		}
		return (x.second.second < y.second.second);
	}
};

ll calc(ll ca) {
	ll cb = cnt - ca;
	ca *= k;
	cb *= k;
	ll res = 0;
	for (int i = 0; i < n; i++) {
		ll cur = min(ca, g[i].first * 1LL);
		res += cur * g[i].second.first;
		ca -= cur;
		if (g[i].first > cur) {
			cur = g[i].first - cur;
			res += cur * g[i].second.second;
			cb -= cur;
		}
	}
	return res;
}

ll calc2(ll cb) {
	ll ca = cnt - cb;
	cb *= k;
	ca *= k;
	ll res = 0;
	for (int i = n - 1; i >= 0; i--) {
		ll cur = min(cb, g[i].first * 1LL);
		res += cur * g[i].second.second;
		cb -= cur;
		if (g[i].first > cur) {
			cur = g[i].first - cur;
			res += cur * g[i].second.first;
			ca -= cur;
		}
	}
	return res;
}

int main() {
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
#ifndef ONLINE_JUDGE
//	freopen("in.txt", "rt", stdin);
//	freopen("out.txt", "wt", stdout);
#endif
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		cin >> s[i] >> a[i] >> b[i];
		g.pb(mp(s[i], mp(a[i], b[i])));
		tot += s[i];
		if (a[i] > b[i]) {
			ga.pb(i);
			suma += s[i];
		} else if (a[i] < b[i]) {
			gb.pb(i);
			sumb += s[i];
		} else {
			ge.pb(i);
			sume += s[i];
		}
	}
	sort(all(g), cmp());
	cnt = tot / k + bool(tot % k);
	ll st = 0, en = cnt;
	while (st < en) {
		ll mid = st + (en - st) / 2;
		if (calc(mid) < calc(mid + 1))
			st = mid + 1;
		else
			en = mid;
	}
	ll res = calc(st);
	st = 0, en = cnt;
	while (st < en) {
		ll mid = st + (en - st) / 2;
		if (calc2(mid) < calc2(mid + 1))
			st = mid + 1;
		else
			en = mid;
	}
	res = max(res, calc2(st));
	cout << res << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int main() {
	int n, S;
	scanf("%d%d", &n, &S);
	long long A = 0, B = 0, ans = 0;
	vector<pair<int, int>> a2b, b2a;
	for (int i = 1; i <= n; ++ i) {
		int s, a, b;
		scanf("%d%d%d", &s, &a, &b);
		if (a >= b) {
			A += s;
			ans += 1LL * s * a;
			a2b.push_back({a - b, s});
		}
		else {
			B += s;
			ans += 1LL * s * b;
			b2a.push_back({b - a, s});
		}
	}
	if ((A + S - 1) / S + (B + S - 1) / S == (A + B + S - 1) / S) {
		cout << ans << endl;
	}
	else {
		long long ans1 = ans, ans2 = ans;
		int cutA = A % S, i = 0;
		sort(a2b.begin(), a2b.end());
		while (cutA) {
			int change = min(cutA, a2b[i].second);
			cutA -= change;
			ans1 -= 1LL * a2b[i].first * change;
			i ++;
		}
		int cutB = B % S; i = 0;
		sort(b2a.begin(), b2a.end());
		while (cutB) {
			int change = min(cutB, b2a[i].second);
			cutB -= change;
			ans2 -= 1LL * b2a[i].first * change;
			i ++;
		}
		ans = max(ans1, ans2);
		cout << ans << endl;
	}
}


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int main() {
	int n, S;
	scanf("%d%d", &n, &S);
	int A = 0, B = 0;
	long long ans = 0;
	vector<pair<int, int>> a2b, b2a;
	for (int i = 1; i <= n; ++ i) {
		int s, a, b;
		scanf("%d%d%d", &s, &a, &b);
		if (a >= b) {
			A += s;
			ans += 1LL * s * a;
			a2b.push_back({a - b, s});
		}
		else {
			B += s;
			ans += 1LL * s * b;
			b2a.push_back({b - a, s});
		}
	}
	if ((A + S - 1) / S + (B + S - 1) / S == (A + B + S - 1) / S) {
		cout << ans << endl;
	}
	else {
		long long ans1 = ans, ans2 = ans;
		int cutA = A % S, i = 0;
		sort(a2b.begin(), a2b.end());
		while (cutA) {
			int change = min(cutA, a2b[i].second);
			cutA -= change;
			ans1 -= 1LL * a2b[i].first * change;
			i ++;
		}
		int cutB = B % S; i = 0;
		sort(b2a.begin(), b2a.end());
		while (cutB) {
			int change = min(cutB, b2a[i].second);
			cutB -= change;
			ans2 -= 1LL * b2a[i].first * change;
			i ++;
		}
		ans = max(ans1, ans2);
		cout << ans << endl;
	}
}


#ifdef __GNUC__
#pragma GCC target("sse4,avx")
#endif
#include <immintrin.h>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <cstdint>
#include <numeric>

int64_t getDiff(const std::vector<std::pair<int64_t, int64_t>>& diff, int64_t slices) {
    int64_t res = 0;
    for (const auto& diffVariant : diff) {
        int64_t transfer = std::min(slices, diffVariant.second);
        res += transfer * diffVariant.first;
        slices -= transfer;
    }
    if (slices > 0) {
        return int64_t(1) << 62;
    }
    return res;
}

void run(std::istream &in, std::ostream &out) {
    int64_t N, S;
    in >> N >> S;
    std::vector<int64_t> s(N), a(N), b(N);
    for (int i = 0; i < N; i++) {
        in >> s[i] >> a[i] >> b[i];
    }
    int64_t total = std::accumulate(s.begin(), s.end(), 0);
    int64_t slices = (total + S - 1) / S;
    std::vector<std::pair<int64_t, int64_t>> adiff;
    std::vector<std::pair<int64_t, int64_t>> bdiff;
    int64_t sum = 0;
    int64_t sumA = 0;
    int64_t sumB = 0;
    for (int i = 0; i < N; i++) {
        if (a[i] > b[i]) {
            sum += a[i] * s[i];
            sumA += s[i];
            adiff.emplace_back(a[i] - b[i], s[i]);
        } else {
            sum += b[i] * s[i];
            sumB += s[i];
            bdiff.emplace_back(b[i] - a[i], s[i]);
        }
    }
    int slicesA = (sumA + S - 1) / S;
    int slicesB = (sumB + S - 1) / S;
    if (slicesA + slicesB == slices) {
        out << sum << std::endl;
        return;
    }
    std::sort(adiff.begin(), adiff.end());
    std::sort(bdiff.begin(), bdiff.end());
    int64_t diff = std::min(getDiff(adiff, sumA % S), getDiff(bdiff, sumB % S));
    out << sum - diff << std::endl;
}

int main() {
  std::cin.sync_with_stdio(false);
  std::cin.tie(nullptr);
  run(std::cin, std::cout);
  return 0;
}


#ifdef __GNUC__
#pragma GCC target("sse4,avx")
#endif
#include <immintrin.h>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <cstdint>
#include <numeric>

int64_t getDiff(const std::vector<std::pair<int64_t, int64_t>>& diff, int64_t slices) {
    int64_t res = 0;
    for (const auto& diffVariant : diff) {
        int64_t transfer = std::min(slices, diffVariant.second);
        res += transfer * diffVariant.first;
        slices -= transfer;
    }
    if (slices > 0) {
        return int64_t(1) << 62;
    }
    return res;
}

void run(std::istream &in, std::ostream &out) {
    int64_t N, S;
    in >> N >> S;
    std::vector<int64_t> s(N), a(N), b(N);
    for (int i = 0; i < N; i++) {
        in >> s[i] >> a[i] >> b[i];
    }
    int64_t total = std::accumulate(s.begin(), s.end(), 0);
    int64_t slices = (total + S - 1) / S;
    std::vector<std::pair<int64_t, int64_t>> adiff;
    std::vector<std::pair<int64_t, int64_t>> bdiff;
    int64_t sum = 0;
    int64_t sumA = 0;
    int64_t sumB = 0;
    for (int i = 0; i < N; i++) {
        if (a[i] > b[i]) {
            sum += a[i] * s[i];
            sumA += s[i];
            adiff.emplace_back(a[i] - b[i], s[i]);
        } else {
            sum += b[i] * s[i];
            sumB += s[i];
            bdiff.emplace_back(b[i] - a[i], s[i]);
        }
    }
    int64_t slicesA = (sumA + S - 1) / S;
    int64_t slicesB = (sumB + S - 1) / S;
    if (slicesA + slicesB == slices) {
        out << sum << std::endl;
        return;
    }
    std::sort(adiff.begin(), adiff.end());
    std::sort(bdiff.begin(), bdiff.end());
    int64_t diff = std::min(getDiff(adiff, sumA % S), getDiff(bdiff, sumB % S));
    out << sum - diff << std::endl;
}

int main() {
  std::cin.sync_with_stdio(false);
  std::cin.tie(nullptr);
  run(std::cin, std::cout);
  return 0;
}


#ifdef __GNUC__
#pragma GCC target("sse4,avx")
#endif
#include <immintrin.h>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <cstdint>
#include <numeric>

int64_t getDiff(const std::vector<std::pair<int64_t, int64_t>>& diff, int64_t slices) {
    int64_t res = 0;
    for (const auto& diffVariant : diff) {
        int64_t transfer = std::min(slices, diffVariant.second);
        res += transfer * diffVariant.first;
        slices -= transfer;
    }
    return res;
}

void run(std::istream &in, std::ostream &out) {
    int64_t N, S;
    in >> N >> S;
    std::vector<int64_t> s(N), a(N), b(N);
    for (int i = 0; i < N; i++) {
        in >> s[i] >> a[i] >> b[i];
    }
    int64_t total = std::accumulate(s.begin(), s.end(), 0);
    int64_t slices = (total + S - 1) / S;
    std::vector<std::pair<int64_t, int64_t>> adiff;
    std::vector<std::pair<int64_t, int64_t>> bdiff;
    int64_t sum = 0;
    int64_t sumA = 0;
    int64_t sumB = 0;
    for (int i = 0; i < N; i++) {
        if (a[i] > b[i]) {
            sum += a[i] * s[i];
            sumA += s[i];
            adiff.emplace_back(a[i] - b[i], s[i]);
        } else {
            sum += b[i] * s[i];
            sumB += s[i];
            bdiff.emplace_back(b[i] - a[i], s[i]);
        }
    }
    int slicesA = (sumA + S - 1) / S;
    int slicesB = (sumB + S - 1) / S;
    if (slicesA + slicesB == slices) {
        out << sum << std::endl;
        return;
    }
    std::sort(adiff.begin(), adiff.end());
    std::sort(bdiff.begin(), bdiff.end());
    int64_t diff = std::min(getDiff(adiff, sumA % S), getDiff(bdiff, sumB % S));
    out << sum - diff << std::endl;
}

int main() {
  std::cin.sync_with_stdio(false);
  std::cin.tie(nullptr);
  run(std::cin, std::cout);
  return 0;
}


#ifdef __GNUC__
#pragma GCC target("sse4,avx")
#endif
#include <immintrin.h>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <cstdint>
#include <numeric>

int64_t getDiff(const std::vector<std::pair<int64_t, int64_t>>& diff, int64_t slices) {
    int64_t res = 0;
    for (const auto& diffVariant : diff) {
        int64_t transfer = std::min(slices, diffVariant.second);
        res += transfer * diffVariant.first;
        slices -= transfer;
    }
    return res;
}

void run(std::istream &in, std::ostream &out) {
    int64_t N, S;
    in >> N >> S;
    std::vector<int64_t> s(N), a(N), b(N);
    for (int i = 0; i < N; i++) {
        in >> s[i] >> a[i] >> b[i];
    }
    int64_t total = std::accumulate(s.begin(), s.end(), int64_t(0));
    int64_t slices = (total + S - 1) / S;
    std::vector<std::pair<int64_t, int64_t>> adiff;
    std::vector<std::pair<int64_t, int64_t>> bdiff;
    int64_t sum = 0;
    int64_t sumA = 0;
    int64_t sumB = 0;
    for (int i = 0; i < N; i++) {
        if (a[i] > b[i]) {
            sum += a[i] * s[i];
            sumA += s[i];
            adiff.emplace_back(a[i] - b[i], s[i]);
        } else {
            sum += b[i] * s[i];
            sumB += s[i];
            bdiff.emplace_back(b[i] - a[i], s[i]);
        }
    }
    int64_t slicesA = (sumA + S - 1) / S;
    int64_t slicesB = (sumB + S - 1) / S;
    if (slicesA + slicesB == slices) {
        out << sum << std::endl;
        return;
    }
    std::sort(adiff.begin(), adiff.end());
    std::sort(bdiff.begin(), bdiff.end());
    int64_t diff = std::min(getDiff(adiff, sumA % S), getDiff(bdiff, sumB % S));
    out << sum - diff << std::endl;
}

int main() {
  std::cin.sync_with_stdio(false);
  std::cin.tie(nullptr);
  run(std::cin, std::cout);
  return 0;
}