#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

inline void MAX(int &a,const int &b) {if(b>a) a=b;}
inline void MIN(int &a,const int &b) {if(b<a) a=b;}
inline int max(const int &a,const int &b) {return a>b?a:b;}
inline int min(const int &a,const int &b) {return a<b?a:b;}

const int N=2e5+5;

int mx,n,m,a[N],b[N];
int tmp[N],len;

struct BIT {
	int c[N];
	long long d[N];
	inline void addc(int pos,int key) {for(int i=pos ; i<=mx ; i+=i&-i) c[i]+=key;}
	inline void addd(int pos,long long key) {for(int i=pos ; i<=mx ; i+=i&-i) d[i]+=key;}
	inline int sumc(int pos) {int res=0;for(int i=pos ; i ; i-=i&-i) res+=c[i];return res;}
	inline long long sumd(int pos) {long long res=0;for(int i=pos ; i ; i-=i&-i) res+=d[i];return res;}
	inline long long query(int key) {
		return sumd(mx)-sumd(key)+1LL*sumc(key)*tmp[key];
	}
}TA,TB;

struct ask {
	int t,x;
	long long y;
	inline ask (int T=0,int X=0,int Y=0) : t(T),x(X),y(Y) {}
}w[N];

int q;

int main() {
	tmp[++len]=0;
	scanf("%d%d",&n,&m);
	scanf("%d",&q);
	for(int i=1 ; i<=q ; ++i) scanf("%d%d%d",&w[i].t,&w[i].x,&w[i].y),tmp[++len]=w[i].y;
	sort(tmp+1,tmp+len+1);
	mx=unique(tmp+1,tmp+len+1)-tmp-1;
	TA.addc(1,n),TB.addc(1,m);
	long long ans=0;
	for(int i=1 ; i<=q ; ++i) {
		int t=w[i].t,x=w[i].x,y=w[i].y,p=lower_bound(tmp+1,tmp+mx+1,y)-tmp;
		if(t==1) {
			int po=lower_bound(tmp+1,tmp+mx+1,a[x])-tmp;
			ans-=TB.query(po),TA.addc(po,-1),TA.addd(po,-a[x]);
			ans+=TB.query(p),TA.addc(p,1),TA.addd(p,y);
			a[x]=y;
		}
		else {
			int po=lower_bound(tmp+1,tmp+mx+1,b[x])-tmp;
			ans-=TA.query(po),TB.addc(po,-1),TB.addd(po,-b[x]);
			ans+=TA.query(p),TB.addc(p,1),TB.addd(p,y);
			b[x]=y;
		}
		printf("%lld\n",ans);
	}
	return 0;
}

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

#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define vpii vector<pair<int,int>>
#define vpll vector<pair<ll,ll>>
#define fr(i,k,n) for (int i = k; i < n; ++i)
#define fri(i,k,n) for (int i = k; i >= n; --i)
#define pb push_back
#define mp make_pair
#define all(arr) arr.begin(),arr.end()
#define ff first
#define ss second

const double pi=3.1415926535897932384626433832795;
const int inf=1e9;
const ll inf2=1e18;
const int mod=1e9+7;

void boost(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
}

const int bs=440,N=2e5+3,M=(N+bs-1)/bs;

ll cnt[2][N],sqcnt[2][M];
ll sum[2][N],sqsum[2][M];
ll t,x,y,z,i1,i2,i3,i4;
ll ans=0;
vector<vll> val(2,vll(N,0));
vi diff;

void fun(ll f){
    z=val[t][x];
    i1=lower_bound(all(diff),z)-diff.begin();
    i3=i1;
    while(i3>=0 && (i3/bs)==(i1/bs)){
        ans+=(f*cnt[i2][i3]*z);
        i3--;
    }
    while(i3>=0){
        ans+=(f*sqcnt[i2][i3/bs]*z);
        i3-=bs;
    }
    i3=i1+1;
    while(i3<N && (i3/bs)==(i1/bs)){
        ans+=f*sum[i2][i3];
        i3++;
    }
    while(i3<N && (i3/bs)<M){
        ans+=f*sqsum[i2][i3/bs];
        i3+=bs;
    }
}

void solve(){
    int n,m,q;
    cin>>n>>m>>q;
    vector<pair<int,pii>> qry(q);
    fr(i,0,q){
        cin>>qry[i].ff>>qry[i].ss.ff>>qry[i].ss.ss;
        qry[i].ff--;
        diff.pb(qry[i].ss.ss);
    }
    diff.pb(0);
    sort(all(diff));
    diff.erase(unique(all(diff)),diff.end());
    cnt[0][0]=sqcnt[0][0]=n;
    cnt[1][0]=sqcnt[1][0]=m;
    fr(i,0,q){
        t=qry[i].ff;x=qry[i].ss.ff;y=qry[i].ss.ss;
        i2=1-t;
        fun(-1);
        cnt[t][i1]--;
        sqcnt[t][i1/bs]--;
        sum[t][i1]-=z;
        sqsum[t][i1/bs]-=z;
        val[t][x]=y;
        fun(1);
        cnt[t][i1]++;
        sqcnt[t][i1/bs]++;
        sum[t][i1]+=y;
        sqsum[t][i1/bs]+=y;
        cout<<ans<<endl;
    }
    return;
}

int main()
{
    boost();

    int tc=1;
    //cin>>tc;
    while(tc--)
        solve();
    return 0;
}


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

#define rep(i,n) for(long (i)=1;(i)<(n+1);(i)++)
#define mod 998244353

int main(){
    int N;
    long long S;

    S = 2329089562801;
    cout << S << endl;

}

#include <iostream>
#include <string>
#include <math.h>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <set>
#include <queue>
#include <deque>
#include <map>
#include <stack>
#include <cmath>
using namespace std;

#define mod 1000000007
#define ten5 100005
#define ten52 200015
#define ten53 300005
#define ten6 1000005
#define PI 3.1415926
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define mkpr(x1,x2) make_pair(x1,x2)
typedef long long int ll;

ll num[ten52];

ll hcf(ll a,ll b)
{
    if(a==b || b==0) return a;
    if(a>b) return hcf(b,a%b);
    else return hcf(a,b%a);
}

int main(void)
{
    ll m=0,n,i=1,j=0,k=1,t=1,ans=2;
    cin>>n;
    for(i=3;i<=n;i++)
    {
        ans=ans*i/hcf(ans,i);
    }
    cout<<ans+1;
    return 0;
}


#ifdef LOGX
#define _GLIBCXX_DEBUG
#endif
#include <bits/stdc++.h>
using namespace std;
//#include <atcoder/all>
//using namespace atcoder;

/*---------macro---------*/
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rep2(i, s, n) for (int i = s; i < (int)(n); ++i)
#define ALL(a) a.begin(),a.end()
#define RALL(a) a.rbegin(),a.rend()
#define mybit(i,j) (((i)>>(j))&1)

/*---------type/const---------*/
typedef long long ll;
typedef unsigned long long ull;
typedef std::string::const_iterator state; //構文解析
const ll big=1000000007;
//const ll big=998244353;
const double EPS=1e-8; //適宜変える
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
const char newl='\n';
struct{
    constexpr operator int(){return -int(1e9)-10;}
    constexpr operator ll(){return -ll(1e18)-10;}
}neginf;
struct{
    constexpr operator int(){return int(1e9)+10;}
    constexpr operator ll(){return ll(1e18)+10;}
    constexpr auto operator -(){return neginf;}
}inf;

/*---------debug---------*/
#ifdef LOGX
#include <template/debug.hpp>
#else
#define dbg(...) ;
#define dbgnewl ;
#define prt(x) ;
#define _prt(x) ;
#endif

/*---------function---------*/
template<typename T> T max(const std::vector<T> &a){T ans=a[0];for(T elem:a){ans=max(ans,elem);}return ans;}
template<typename T> T min(const std::vector<T> &a){T ans=a[0];for(T elem:a){ans=min(ans,elem);}return ans;}
template<typename T,typename U> bool chmin(T &a,const U b){if(a>b){a=b;return true;}return false;}
template<typename T,typename U> bool chmax(T &a,const U b){if(a<b){a=b;return true;}return false;}
bool valid(int i,int j,int h,int w){return (i>=0 && j>=0 && i<h && j<w);}
template<class T,class U>T expm(T x,U y,const ll mod=big){T res=1;while(y){if(y&1)(res*=x)%=mod;(x*=x)%=mod;y>>=1;}return res;}
template<class T,class U>T exp(T x,U y){T res=1;while(y){if(y&1)res*=x;x*=x;y>>=1;}return res;}

constexpr long long primetest[]={2,3,61};
constexpr long long primetest_big[]={2,325,9375,28178,450775,9780504,1795265022};
//O(N^(1/4))
//N>2^32では__int128_tが使える環境に限る
bool isprime(const long long x){
    if(x==0 || x==1)return false;
    const long long d=(x-1)/((x-1)&-(x-1));
    if(x<(1LL<<32)){
        if(x==2 || x==3 || x==61)return true;
        for(long long e:primetest){
            long long t=d;
            long long y=expm(e,t,x);
            if(y==1)continue;//とりあえずテスト通過.
            while(y!=x-1){//y=-1になったらその時点でテスト通過.
                y=(y*y)%x;//y=e^2t modx.
                if(y==1 || t==x-1)return false;//y==1:1の平方根に1,-1以外が存在.t==x-1:e^t!=1.
                t<<=1;
            }
        }
        return true;
    }
    else{
        for(__int128_t e:primetest_big){
            long long t=d;
            __int128_t y=expm(e,t,x);
            if(y==1)continue;//とりあえずテスト通過.
            while(y!=x-1){//y=-1になったらその時点でテスト通過.
                y=(y*y)%x;//y=e^2t modx.
                if(y==1 || t==x-1)return false;//y==1:1の平方根に1,-1以外が存在.t==x-1:e^t!=1.
                t<<=1;
            }
        }
        return true;
    }
}

int main(){
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.precision(10);
    /*--------------------------------*/

    ll a,b;cin >> a >> b;
    vector<ll> ps;
    rep(i,b-a+1){
        if(isprime(i))ps.emplace_back(i);
    }
    vector<int> has;
    for(ll i=a;i<=b;i++){
        int now=0;
        rep(j,ps.size())if(i%ps[j] == 0)now|=1<<j;
        has.emplace_back(now);
    }
    vector<ll> dp(1<<ps.size());
    dp[0]=1;
    rep(i,b-a+1)for(int S=(1<<ps.size())-1;S>=0;S--){
        if((S&has[i]) == 0)dp[S|has[i]]+=dp[S];
    }
    ll ans=0;
    for(ll x:dp){
        ans+=x;
    }
    cout << ans << newl;
}

#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ld = long double;

#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define ALL(x) ((x).begin()), ((x).end())

#define READ(x) (cin >> (x))
#define WRITE_N(x) (cout << (x) << endl)
#define WRITE(x) (cout << (x))
#define WRITE_YESNO(x) (WRITE_N((x) ? "Yes" : "No"))

#define PRECISE_COUT std::cout << std::setprecision(15) << std::fixed

bool xor_logic(bool x, bool y) { return (x && y) || (!x && !y); }

int main() {
  // get values from input
  cin.tie(0);
  ios::sync_with_stdio(false);

  int A, B;
  cin >> A >> B;

  // main procedure

  // output
  cout << 2 * A + 100 - B << endl;

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
typedef long long int ll;

int main() {
        string n; cin >> n;
        int numbers[n.length()];
        int i = 0;
        int sum = 0;
        for (auto c : n) {
                numbers[i] = c - '0';
                sum += numbers[i];
                ++i;
        }

        int t = 0;

        for (int i=0; i<n.length(); ++i) {
                for (int j=0; j<=n.length()-i; ++j) {
                        t = 0;
                        for (int k=j; k<j+i; ++k) {
                                t += numbers[k];
                        }
                        if ((sum-t) % 3 == 0) {
                                cout << i << endl;
                                return 0;
                        }
                }
        }
        cout << -1 << endl;

}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
int n;
const int maxn = 5e5 + 10;
char s[maxn], t[maxn];
queue<int> q;
int main() {
	while(~scanf("%d%*c", &n)) {
		while(!q.empty()) q.pop();
		int cnt1 = 0, cnt2 = 0; ll ans = 0;
		for(int i = 1; i <= n; i++) scanf("%1d", &s[i]), cnt1 += s[i];
		for(int i = 1; i <= n; i++) scanf("%1d", &t[i]), cnt2 += t[i];
		for(int i = 1; i <= n; i++) if(s[i] == 1) q.push(i);
		for(int i = 1; i <= n; i++) {
			if(t[i] == 0) {
				if(!q.empty() && q.front() <= i) {
					cnt1 -= 2;
					if(cnt1 < cnt2) {
						ans = -1;
						break;
					}
					int x = q.front(); q.pop();
					int y = q.front(); q.pop();
					ans += y-x;
				}
			}
			else {
				int x = q.front(); q.pop();
				ans += x-i;
			}
		}
		printf("%lld\n", ans);
	}
	//system("pause");
    return 0;
}

#include<iostream>
#include<assert.h>
#define int long long
#define endl '\n'
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define infi INT_MAX
#define rinfi INT_MIN
#define inf LLONG_MAX
#define rinf LLONG_MIN
#define ff first
#define ss second
#ifndef ONLINE_JUDGE
#define line cout<<"here - "<<__LINE__<<"\n";
#define dbg(a) cout<<#a<<" --> "<<(a)<<"\n";
#define db(a,b) cout<<#a<<" --> "<<(a)<<"\n";cin>>b;
#else
#define line
#define dbg(a)
#define db(a,b)
#endif
char _;
using namespace std;
int i,j,a;
 string s,t;
void go()
{
    while(i<a && s[i]=='0')
        i++;
}
main()
{
//    fast
    int tc=1,k;
//    cin>>tc;
//    getchar();
    while(tc--)
    {
     cin>>a;
     cin>>s>>t;
     int ans=0;
     i=0;j=0;
     a=s.size();
     while(j<a)
     {
         while(i<a && s[i]=='0')
            i++;
         while(j<a && t[j]=='0')
            j++;
            int cnt=i;
            int ok=0,m=0;
            while(i<j && j<a && i<a)
            {
                int cnt=i;
                i++;
               go();
               ans+=i-cnt;
               i++;
               go();
            }
            dbg(ans)
         if(j<a && t[j]=='1')
         {
             if(i<j || i>=a)
             {
                 cout<<-1<<endl;
                 return 0;
             }

         }
         else if(j==a){
            break;
         }
         dbg(i) dbg(j)
         ans+=i-j;
         i++;
         j++;

     }
     dbg(i) dbg(j)
     assert(i<=a);
     assert(j<=a);
     for(;i<a;i++)
     {
         if(s[i]=='1')
         {
              int cnt=i;
              i++;
              go();
              if(i>=a)
              {
                  cout<<-1<<endl;
                  return 0;
              }
              ans+=i-cnt;
         }
     }
     cout<<ans<<endl;
     i=0,j=0;
    }
}


#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
//#include<atcoder/all>
//using namespace atcoder;
#include<iostream>
#include<cstring>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int IM = 2e9;
int dat[400004];

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

	int N;
	cin >> N;
	dat[0] = -IM;
	ll kotae = -IM * ll(N);
	for (int i = N + 1; i > 1; i--) {
		cin >> dat[i];
		kotae += dat[i];
	}

	for (int i = 2; i < N + 2; i++) {

		int p = 2 + (dat[2] > dat[3]);
		int v = dat[i] - IM;
		while (v > dat[p]) {
			dat[p >> 1] = dat[p];
			p <<= 1;
			p += dat[p] > dat[p + 1];
		}
		dat[p >> 1] = v;

		int a;
		cin >> a;
		kotae += a;
		p = i;
		v = a - IM;
		while (v < dat[p >> 1]) dat[p] = dat[p >> 1], p >>= 1;
		dat[p] = v;

		kotae -= dat[1];
	}

	co(kotae);

	Would you please return 0;
}

#include <iostream>
#include <queue>
using namespace std;
typedef long long ll;

int main()
{
    int n;
    cin >> n;
    ll a[400005];
    for(int i = 0; i < n * 2; i++) cin >> a[i];
    priority_queue<ll> que;
    ll ans = 0;
    for(int i = 0; i < n; i++){
        que.push(a[i]);
        que.push(a[n * 2 - i - 1]);
        ans += que.top();
        que.pop();
    }
    cout << ans << endl;
}


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

int main(){
  int a,b,w,x,y;
  cin >> a >> b >> w;
  w *= 1000;
  if((w + b -1) / b * a <= w){
    cout <<  (w + b - 1) / b << endl;;
  }
  if((w / a) * b >= w){
    cout << w / a << endl;
  }
  else{
    cout << "UNSATISFIABLE" << endl;
  }
}


#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <vector>

#define mkp make_pair
#define mkt make_tuple
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define all(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
// const ll MOD = 998244353;
template <class T>
void chmin(T &a, const T &b) {
    if (a > b) a = b;
}
template <class T>
void chmax(T &a, const T &b) {
    if (a < b) a = b;
}

void add(ll &a, ll b) {
    a = (a + b) % MOD;
}

void mul(ll &a, ll b) {
    a %= MOD;
    b %= MOD;
    a = a * b % MOD;
}

void solve() {
    int N;
    cin >> N;
    vector<ll> A(N);
    rep(i, N) cin >> A[i];

    vector<vector<vector<int>>> idxs(N + 1, vector<vector<int>>(N + 1));
    for (int k = 1; k <= N; k++) {
        ll sum = 0;
        idxs[k][0].push_back(0);
        for (int i = 0; i < N; i++) {
            sum += A[i];
            sum %= k;
            idxs[k][sum].push_back(i + 1);
        }
    }

    vector<vector<int>> nxt(N + 1, vector<int>(N + 1, -1));
    for (int k = 1; k <= N; k++) {
        for (int rest = 0; rest < k; rest++) {
            for (int j = 0; j + 1 < idxs[k][rest].size(); j++) {
                nxt[idxs[k][rest][j]][k] = idxs[k][rest][j + 1];
            }
        }
    }

    vector<vector<ll>> dp(N + 1, vector<ll>(N + 1, -1));
    auto rec = [&](auto &&rec, int now, int divisor) -> ll {
        if (now == N) return 1;
        if (dp[now][divisor] != -1) return dp[now][divisor];

        ll sum = 0;
        ll res = 0;
        if (nxt[now][divisor] != -1) {
            add(res, rec(rec, nxt[now][divisor], divisor));
            if (nxt[now][divisor] < N) add(res, rec(rec, nxt[now][divisor], divisor + 1));
        }

        return dp[now][divisor] = res;
    };

    ll ans = rec(rec, 0, 1);
    cout << ans << endl;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    solve();

    return 0;
}

//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
#define FOR(i, a, b) for (ll i = (a); i < (b); ++i)
#define REP(i, n) FOR(i,0,n)
#define BFOR(bit,a,b) for(int bit = (a); bit < (1<<(b)); ++bit)
#define BREP(bit,n) BFOR(bit,0,n)
using namespace std;
using ll = long long;

int main() {
    ll n;
    string t;
    cin >> n >> t;
    if(t == "1"){
        ll ans = 1e10 * 2;
        cout << ans << endl;
        return 0;
    }
    if(t == "0"){
        ll ans = 1e10;
        cout << ans << endl;
        return 0;
    }
  	if(t == "00"){
        ll ans = 0;
        cout << ans << endl;
        return 0;
    }
  	if(t == "10"){
        ll ans = 1e10;
        cout << ans << endl;
        return 0;
    }
  	if(t == "01"){
        ll ans = 1e10-1;
        cout << ans << endl;
        return 0;
    }
    if(t == "11"){
        ll ans = 1e10;
        cout << ans << endl;
        return 0;
    }
  	if(t[0] != '1' || t[1] != '1' || t[2] != '0'){
      if(t[0] == '1' && t[1] == '0'){
        t = "1"+t;
        n++;
      }
      else if(t[0] == '0'){
        t = "11"+t;
        n += 2;
      }
      else{
        cout << 0 << endl;
      	return 0;
      }
    }
    if(t[n-3] != '1' || t[n-2] != '1' || t[n-1] != '0'){
      if(t[n-1] == '1' && t[n-2] == '1'){
        t = t+"0";
        n++;
      }
      else if(t[n-1] == '1'){
        t = t+"10";
        n += 2;
      }
    }
  	if(n % 3 != 0){
      cout << 0 << endl;
      return 0;
    }
  	string s;
  	REP(i,n/3) s += "110";
    ll ans;
  	if(s == t) ans = 1e10 - n/3+1;
    else ans = 0;
    cout << ans << endl;
}


#include <bits/stdc++.h>
// #include <atcoder/modint>
#define rng(a) a.begin(),a.end()
#define rrng(a) a.rbegin(),a.rend()
#define INF 2000000000000000000
#define ll long long
#define ld long double
#define pll pair<ll, ll>
using namespace std;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  ll N;
  cin >> N;
  vector<pll> data(N);
  vector<vector<ll>> connection(N);
  for (ll i = 0; i < N - 1; ++i) {
    ll a, b;
    cin >> a >> b;
    a -= 1, b -= 1;
    connection.at(a).push_back(b);
    connection.at(b).push_back(a);
    data.at(i) = {a, b};
  }
  queue<pll> q;//now, par
  vector<ll> par(N, -1);
  q.push({0, -1});
  while (!q.empty()) {
    ll now = q.front().first, p = q.front().second;
    q.pop();
    for (ll i = 0; i < connection.at(now).size(); ++i) {
      ll next = connection.at(now).at(i);
      if (next == p) {
        continue;
      }
      par.at(next) = now;
      q.push({next, now});
    }
  }
  vector<ll> ans(N, 0);
  ll Q;
  cin >> Q;
  ll sum = 0;
  for (ll i = 0; i < Q; ++i) {
    ll t, e, x;
    cin >> t >> e >> x;
    e -= 1;
    ll a = data.at(e).first, b = data.at(e).second;
    if (t == 2) {
      swap(a, b);
    }
    if (par.at(a) == b) {
      ans.at(a) += x;
    }
    else {
      ans.at(b) -= x;
      sum += x;
    }
  }
  q.push({0, -1});
  while (!q.empty()) {
    ll now = q.front().first, p = q.front().second;
    q.pop();
    for (ll i = 0; i < connection.at(now).size(); ++i) {
      ll next = connection.at(now).at(i);
      if (next == p) {
        continue;
      }
      ans.at(next) += ans.at(now);
      q.push({next, now});
    }
  }
  for (ll i = 0; i < N; ++i) {
    cout << ans.at(i) + sum << "\n";
  }
}

#include <bits/stdc++.h>
using namespace std;
using lint = long long int;
using P = pair<int, int>;
using PL = pair<lint, lint>;
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
#define ALL(a)  (a).begin(),(a).end()
constexpr int MOD = 1000000007;
constexpr lint B1 = 1532834020;
constexpr lint M1 = 2147482409;
constexpr lint B2 = 1388622299;
constexpr lint M2 = 2147478017;
constexpr int INF = 2147483647;
void yes(bool expr) {cout << (expr ? "Yes" : "No") << "\n";}
template<class T>void chmax(T &a, const T &b) { if (a<b) a=b; }
template<class T>void chmin(T &a, const T &b) { if (b<a) a=b; }
struct Node;
vector<Node> V;
struct Node {
  vector<int> nbr;
  int d;
  lint ans = 0;
  lint tmp = 0;
  bool vst = false;
  void dfsd(int _d) {
    d = _d;
    vst = true;
    for(int x : nbr) if(!V[x].vst) V[x].dfsd(_d+1);
  }
  void dfs(lint val) {
    ans = val + tmp;
    vst = true;
    for(int x : nbr) if(!V[x].vst) V[x].dfs(ans);
  };
};
int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int N;
  cin >> N;
  vector<int> a(N-1), b(N-1);
  V = vector<Node>(N);
  REP(i, N-1) {
    cin >> a[i] >> b[i];
    a[i]--; b[i]--;
    V[a[i]].nbr.push_back(b[i]);
    V[b[i]].nbr.push_back(a[i]);
  }
  V[0].dfsd(0);
  int Q;
  cin >> Q;
  lint all = 0;
  REP(q, Q) {
    lint t, e, x;
    cin >> t >> e >> x;
    e--;
    if(t == 1) {
      if(V[a[e]].d < V[b[e]].d) {
        V[b[e]].tmp -= x;
        all += x;
      } else {
        V[a[e]].tmp += x;
      }
    } else {
      if(V[a[e]].d > V[b[e]].d) {
        V[a[e]].tmp -= x;
        all += x;
      } else {
        V[b[e]].tmp += x;
      }
    }
  }
  REP(i, N) V[i].vst = false;
  V[0].dfs(0);
  REP(i, N) cout << V[i].ans + all << "\n";
}


/*
 * @Author: zhl
 * @Date: 2020-10-18 20:56:45
 */
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int A[N], B[N], n;

int ans;
void dfs(int now, stack<int> s, int sum) {
	if (now == n) {
		if (s.empty()) {
			ans = max(ans, sum);
			return;
		}
	}
	if (!s.empty()) {
		int tp = s.top();
		int d = max(A[tp] + A[now + 1], B[tp] + B[now + 1]);
		s.pop();
		dfs(now + 1, s, sum + d);
		s.push(tp);
	}
	if (n - now >= s.size()) {
		s.push(now + 1);
		dfs(now + 1, s, sum);
	}
}
int main() {
	cin >> n;
	long long ans = 0;
	for (int i = 1; i <= n; i++)cin >> A[i], ans += A[i];
	for (int i = 1; i <= n; i++)cin >> B[i], B[i] -= A[i];

	vector<int>a, b;
	for (int i = 1; i <= n; i++) {
		if (i & 1)a.push_back(B[i]);
		else b.push_back(B[i]);
	}
	sort(a.begin(), a.end(), greater<int>());
	sort(b.begin(), b.end(), greater<int>());

	for (int i = 1; i <= n / 2; i++) {
		if (a[i - 1] + b[i - 1] > 0) {
			ans += a[i - 1] + b[i - 1];
		}
	}
	cout << ans << endl;

}

#include <bits/stdc++.h>

#define ll long long
#define sz(x) ((int) (x).size())
#define all(x) (x).begin(), (x).end()
#define vi vector<int>
#define pii pair<int, int>
#define rep(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;
template<typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    vector<ll> a(n), b(n);
    ll cost = 0;
    rep(i, 0, n) {
        cin >> a[i];
        cost += a[i];
    }
    vector<ll> ve[2];
    rep(i, 0, n) {
        cin >> b[i];
        ve[i % 2].push_back(b[i] - a[i]);
    }
    sort(all(ve[0]), greater<>());
    sort(all(ve[1]), greater<>());
    int idx = 0;
    while(idx < n / 2 && ve[0][idx] + ve[1][idx] > 0) {
        cost += ve[0][idx] + ve[1][idx];
        idx++;
    }
    cout << cost << '\n';
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <iomanip>
#include <functional>
#include <deque>
#include <stack>
#include <queue>
#include <bitset>
#include <map>
#include <set>
#include <unordered_set>
using namespace std;
typedef long long ll;
#define rep(i,n) for (ll i = 0; i < (ll)(n); i++)
#define REP(i,n) for (ll i = 1; i <= (ll)(n); i++)
#define all(v) v.begin(), v.end()
#define pb push_back
#define fcout cout<<fixed<<setprecision(15)
#define PI 3.1415926535897932384626433832795028841971693993751058209749445923078160628620899
const ll MOD = 1000000007;
const ll MOD2 = 998244353;
const ll INF = 1000000000000000000;
const ll NIL = -1;
const ll dx[4] = { 0,1,0,-1 };
const ll dy[4] = { 1,0,-1,0 };

double N, D, H, d[1010], h[1010];

int main() {
	cin >> N >> D >> H;
	rep(i, N) cin >> d[i] >> h[i];
	double ans = 0;
	rep(i, N) {
		double k;
		k = (H - h[i]) * D / (D - d[i]);
		ans = max(ans, H - k);
	}
	fcout << ans << endl;
	return 0;
}

#include <iostream>

using namespace std;

int main(){
	ios::sync_with_stdio(false);
  	cin.tie(0);
  	int a,b,c,d;
  	cin>>a>>b>>c>>d;
  	cout<<a*d-c*b<<'\n';
}


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

int main(){

  int A,B;
  cin >> A >> B;

  cout << (A+B)/2 << " " << (A-B)/2 << endl;

}

#include <bits/stdc++.h>
#define int long long

using namespace std;
int32_t main(){

    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin>>n;
    string s; cin>>s;

    string t;
    while((int)t.size() < n+4) t+="110";
    int ans=0;
    for(int i=0;i<3;i++){
        if(s!=t.substr(i,n)) continue;
        ans+=(int)1e10-(n+i-1)/3;
    }
    cout<<ans;
    return 0;
}


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

int main()
{
    ll i,j,n;
    n = 4;
    vector<ll> a(n);
    ll s = 0;
    for(i=0;i<n;i++) cin>>a[i], s+=a[i];
    for(i=0;i<n;i++)
    {
        if(s-a[i] == a[i])
        {
            cout<<"Yes";
            return 0;
        }
    }
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(s-(a[i]+a[j]) == a[i]+a[j])
            {
                cout<<"Yes";
                return 0;
            }
        }
    }
    cout<<"No";
}

#include "bits/stdc++.h"
using namespace std;
#define dracarys ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC target("avx2")

#define ll long long
#define ld long double
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define dbg(x) cout << "[ " << x << " ] "
#define ump unordered_map

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count();
struct chash{
    int operator()(int x) const { return x ^ RANDOM; }
};

void solve(int tt){
    int n = 4;
    vector<ll> v(n);
    for (auto& it : v) cin >> it;
    ll sum = accumulate(all(v),0);
    bool flag = 0;
    for (int i = 0;i < (1 << n);i++){
        ll sub = 0;
        for (int j = 0;j < n;j++){
            if (i & (1 << j)){
                sub += v[j];
            }
        }
        flag |= (sub * 2ll == sum);
    }
    if (sum % 2 == 0 and flag){
        cout << "Yes\n";
    }
    else
        cout << "No\n";
}

int main(){

    // #ifndef ONLINE_JUDGE
    //     freopen("input.txt", "r", stdin);
    //     freopen("output.txt", "w", stdout);
    // #endif

    dracarys

    int tt = 0,t = 1;
    //cin >> t;

    while(t--){solve(++tt);}

    cerr << "processor time: " << clock() / (double) CLOCKS_PER_SEC << "s    ";

    return 0;
}


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

int main () {
	 ios::sync_with_stdio(false);
	 cin.tie(nullptr);
	 cout.tie(nullptr);
	 int T = 1;
	 //~ cin >> T;
	 for (int t = 1; t <= T; ++t) {
		 int n;
		 cin >> n;
		 int input[n + 1];
		 for (int i = 1; i <= n; ++i) {
			 cin >> input[i];
		 }
		 set<int> nums;
		 nums.insert(0);
		 for (int i = 1; i <= n; ++i) {
			 nums.insert(i);
		 }
		 for (int i = 1; i <= n; ++i) {
			 set<int>:: iterator it = nums.begin();
			 if (*it == input[i]) {
				 nums.erase(it);
				 it = nums.begin();
				 cout << *it << "\n";
			 } else {
				 while (i <= n and *it != input[i]) {
					 cout << *it << "\n";
					 nums.erase(input[i]);
					 ++i;
				 }
				 if (i <= n) {
					 nums.erase(it);
					 it = nums.begin();
					 cout << *it << "\n";
				 }
			 }
		 }
	 }
}

#include "bits/stdc++.h"
// #include <bits/stdc++.h>
using namespace std;
// #include <atcoder/all>
// using namespace atcoder;
using ll = long long;

template <typename T>
void print_vec(const vector<T>& v, bool is_reverse=false, ll num=0){
  if(num == 0) num = (ll)v.size();
  cout << endl; cout << "i=  ";for(ll i=0; i<num; i++) cout << i << "   ";cout << endl;
  cout << "    ";
  if(is_reverse) for(ll i=num-1; i>=0; i--){ cout<<v[i]; if(i!=0) cout<<"   ";}
  else for(ll i=0; i<num; i++){ cout<<v[i]; if(i!=num-1) cout<<"   ";}
  cout << endl;
}

// template <typename T>
// void print_pairvec(const vector<T> &v, ll num=0){
//   if(num == 0) num = (ll)v.size();
//   cout << endl; for(ll i=0; i<num; i++){ cout << v[i].first << " " << v[i].second << endl;}
// }
template <typename T>
void print_pairvec(const T &_pair, ll num=0){
  cout << endl; for(pair<ll, int> x: _pair){ cout << x.first << " " << x.second << endl;}
}

template <typename T>
void print_vec2(const vector<vector<T>>& v){
  cout << endl; cout << "       ";
  for(ll i=0; i<v[0].size(); i++) cout << i << "   ";
  cout << endl;
	for(ll i=0; i<v.size(); i++){
		cout << "i=" << i << ":   ";
		for(ll j=0; j<v[i].size(); j++){
			if(v[i][j] == 0) cout << "\x1B[0m" << v[i][j] << "   ";
      else cout << "\x1B[31m" << v[i][j] << "   ";//https://stackoverrun.com/ja/q/12618775
		}
		cout << "\x1B[0m" << endl;
	}
}

int main(){
  ll N;
  cin >> N ;
  vector<ll> p(N);

  vector<bool> is_p(N+1, false);
  for(int i=0; i<N; i++) cin >> p[i];
  // for(int i=0; i<N; i++) is_p[p[i]] = true;

  ll ans = 0;
  for(int i=0; i<N; i++){
    is_p[p[i]] = true;
    while(is_p[ans] == true) ans++;
    cout << ans << endl;
  }

  // cout << ans << endl;

  return 0;
  // cout << fixed;//小数点を確実に10桁で表示するためのもの
  // cout << setprecision(10);
}


/*#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
*/

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

#define ll long long
#define f first
#define s second
#define Fast ios_base::sync_with_stdio(false);cin.tie(NULL);
typedef pair<ll , pair<ll, ll> > pi;
int pow(int x,int y){
    int res=1;
    while(y){
        if(y&1) res*=x;
        y>>=1;
        x*=x;
    }
    return res;
}
struct Compare {
    constexpr bool operator()(pi const & a,
                              pi const & b) const noexcept
    { return a.first < b.first || (a.first == b.first && a.second.first > b.second.first); }

};
void prefix_function( string s,ll arr[] )
{
     long long border=0; arr[0]=0;
    for(long long i=1;i<s.size();i++)
    {
      while(border>0 && s[i]!=s[border])
        border=arr[border-1];

     if(s[i]==s[border])
         border++;
      else
       border=0;

      arr[i]=border;
    }
}//send mod-2 for a^-1 if mod is a prime number

ll mod=998244353;
ll add( ll a , ll b)
{
    return (((a%mod)+(b%mod))%mod);
}
ll mul(ll a,ll b)
{
  return (((a%mod)*(b%mod))%mod);
}
ll binpow(ll a, ll b) {
    ll res = 1;
    while (b) {
        if (b & 1) res = mul(res, a);
        a = mul(a, a);
        b >>= 1;
    }
    return res;
}
ll subs(ll a,ll b)
{
    return (((a%mod)-(b%mod)+mod)%mod);
}
ll dv(ll a,ll b)
{
    ll inv=binpow(b,mod-2);
    return mul(a,inv);
}

ll dsu_arr[100000];
ll dsu_sz[100000];
void dsu(ll n)
{
    for(ll i=0;i<=n;i++)
    {
        dsu_arr[i]=i;
        dsu_sz[i]=1;
    }
}
ll find(ll x)
{
     ll root=x;
    while (root!=dsu_arr[root])
    {
        root=dsu_arr[root];
    }
    while(x!=dsu_arr[x])
    {
        dsu_arr[x]=root;
        x=dsu_arr[x];
    }
    return root;
}
ll merge(ll x,ll y)
{
    ll root1=find(x);
    ll root2=find(y);

    if(root1==root2)
    return 0ll;

    if(dsu_sz[x]>dsu_sz[y]){
    dsu_arr[root2]=root1;
    dsu_sz[root1]+=dsu_sz[root2];
    }
    else
    {
         dsu_sz[root2]+=dsu_sz[root1];
        dsu_arr[root1]=root2;
    }
    return 1ll;
}
/*
vector<ll>adj[100005];
bool vis[100005];
ll dist[100005];
void bfs(ll c)
{
  vis[c]=true;
  dist[c]=0;
  queue<ll>q;
  q.push(c);
while(!q.empty())
{
    ll x=q.front();
    q.pop();

    for(ll i=0;i<adj[x].size();i++)
    {
        ll y=adj[x][i];
        if(!vis[y])
        {
            vis[y]=true;
            dist[y]=dist[x]+1;

            q.push(y);
        }
    }

}
}
*/

int main()
{
    Fast
ll n;
     string s;
     cin>>s;
      n=s.size();
     vector<ll>sura;
    ll mx=-1;
  for(ll mask=0;mask<(1<<n);mask++)
  {
     ll sum=0;
     ll h=0;
      for(ll i=0;i<n;i++ )
      {
          if(mask& (1<<i))
          {
              h++;
              sum+=(s[i]-'0');
          }
      }
      if(sum%3==0 && sum>0)
      {
          mx=max(mx,h);
      }
  }
  if(mx==-1)
  {
      cout<<mx<<endl;
  }
  else
  {
      cout<<n-mx<<endl;
  }

}

#include <algorithm>
#include <vector>
#include <cstdio>
#include <cmath>
#define int long long
const int N = 100005, INF = 0x3f3f3f3f3f3f3f3fll;
int n, x, ans = INF, cnt, tot;
std::vector<int> R, G, B, a[3], b[2];
char c[5];
int find(std::vector<int> a, std::vector<int> b) {
    int an = INF;
    if(a.size() == 0 || b.size() == 0) return an;
    for(int i = 0; i < (signed)a.size(); i++) {
        int pos = std::lower_bound(b.begin(), b.end(), a[i]) - b.begin();
        int x = INF;
        if(pos == 0) x = std::abs(b[0] - a[i]);
        else if(pos == b.end() - b.begin()) x = std::abs(b[pos-1]-a[i]);
        else x = std::min(std::abs(b[pos]-a[i]), std::abs(b[pos-1]-a[i]));
        an = std::min(an, x);
    }
    return an;
}
signed main() {
    scanf("%lld", &n);
    n = 2 * n;
    for(int i = 1; i <= n; i++) {
        scanf("%lld%s", &x, c);
        if(c[0] == 'R') R.push_back(x);
        if(c[0] == 'G') G.push_back(x);
        if(c[0] == 'B') B.push_back(x);
    }
    // printf("%d %d %d", R.size(), G.size(), B.size());
    if(R.size() % 2 == 0 && G.size() % 2 == 0 && B.size() % 2 == 0)
        return puts("0"), 0;
    if(R.size() % 2 == 1) a[++cnt] = R; else b[++tot] = R;
    if(G.size() % 2 == 1) a[++cnt] = G; else b[++tot] = G;
    if(B.size() % 2 == 1) a[++cnt] = B; else b[++tot] = B;
    std::sort(a[1].begin(), a[1].end());
    std::sort(a[2].begin(), a[2].end());
    std::sort(b[1].begin(), b[1].end());
    ans = find(a[1], a[2]);
    ans = std::min(find(a[1], b[1]) + find(a[2], b[1]), ans);
    printf("%lld", ans);
    return 0;
}


#include <bits/stdc++.h>
#if __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;
#endif
using namespace std;
using ll = long long;
struct Edge
{
    ll to;
    ll cost;
};
using Graph = vector<vector<Edge>>;
using P = pair<ll, ll>;
#define mp make_pair
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define RSORT(v) sort((v).rbegin(), (v).rend())
#define ALL(v) (v).begin(), v.end()
const ll MOD = 1000000007;
const ll nmax = 8;
const ll INF = LLONG_MAX;
const int MAX = 510000;
bool graph[nmax][nmax];
long long fac[MAX], finv[MAX], inv[MAX];

void COMinit()
{
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++)
    {
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

ll COM(int n, int k)
{
    if (n < k)
        return 0;
    if (n < 0 || k < 0)
        return 0;

    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

vector<vector<ll>> dist = vector<vector<ll>>(nmax, vector<ll>(nmax, INF));
void warshall_floyd(ll n)
{
    for (size_t i = 0; i < n; i++)
    {
        for (size_t j = 0; j < n; j++)
        {
            for (size_t k = 0; k < n; k++)
            {
                dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k]);
            }
        }
    }
}

ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

ll lcm(ll a, ll b)
{
    ll g = gcd(a, b);
    return a / g * b;
}

ll mulMod(ll a, ll b)
{
    return (((a % MOD) * (b % MOD)) % MOD);
}

ll powMod(ll a, ll p)
{
    if (p == 0)
    {
        return 1;
    }
    else if (p % 2 == 0)
    {
        ll half = powMod(a, p / 2);
        return mulMod(half, half);
    }
    else
    {
        return mulMod(powMod(a, p - 1), a);
    }
}

ll ceil(ll a, ll b)
{
    return (a + b - 1) / b;
}

void solve(long long N, long long C, std::vector<long long> a, std::vector<long long> b, std::vector<long long> c)
{
    map<ll, ll> zip;
    map<ll, ll> unzip;
    vector<ll> all;
    for (int i = 0; i < N; i++)
    {
        all.push_back(a[i]);
        all.push_back(b[i]);
    }

    SORT(all);
    all.erase(unique(ALL(all)), all.end());
    for (int i = 0; i < all.size(); i++)
    {
        zip[all[i]] = i;
        unzip[i] = all[i];
    }

    vector<ll> sum(all.size() + 1, 0);

    for (int i = 0; i < N; i++)
    {
        sum[zip[a[i]]] += c[i];
        sum[zip[b[i]]] -= c[i];
    }

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

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

    ll ans = 0;
    for (int i = 0; i < sum.size() - 2; i++)
    {
        // cout << unzip[i] << " " << unzip[i + 1] << " " << sum[i] << endl;
        if (sum[i] > C)
        {
            ans += (unzip[i + 1] - unzip[i]) * C;
        }
        else
        {
            ans += (unzip[i + 1] - unzip[i]) * sum[i];
        }
        // cout << sum[i] << " ";
    }
    // if (sum[sum.size() - 2] > C)
    // {
    //     ans += C;
    // }
    // else
    // {
    //     ans += sum[sum.size() - 2];
    // }
    // cout << endl;

    cout << ans << endl;
}

int main()
{

    long long N;
    scanf("%lld", &N);
    long long C;
    scanf("%lld", &C);
    std::vector<long long> a(N);
    std::vector<long long> b(N);
    std::vector<long long> c(N);
    for (int i = 0; i < N; i++)
    {
        scanf("%lld", &a[i]);
        scanf("%lld", &b[i]);
        scanf("%lld", &c[i]);
        ++b[i];
    }
    solve(N, C, std::move(a), std::move(b), std::move(c));
    return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <numeric>
#include <string>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <set>
#include <cmath>
#include <bitset>
#include <iomanip>

using namespace std;

using ll = long long;
using ull = unsigned long long;

#define all(x) (x).begin(),(x).end()
#define rep(i,n) for(int i = 0;(i) < ((int)(n));++(i))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() )
#define test(a) cout<<"line:"<<__LINE__<<"["<<(#a)<<": "<<(a)<<"]"<<endl

constexpr int INF = 1e9+7;
constexpr ll INFL = 9*1e18;

constexpr int dx[4] = { 1, 0, -1, 0 };
constexpr int dy[4] = { 0, 1, 0, -1 };

// constexpr int dx[8] = {1, 1, 0,-1,-1,-1, 0, 1};
// constexpr int dy[8] = {0, 1, 1, 1, 0,-1,-1,-1};

int inline digit(ll num){int tmp = 0;while(num){tmp++;num/=10;}return tmp;} // 桁数
ull inline power(ull a,ull b){ull res = 1;rep(i,b)res *= a;return res;}
template<typename T>inline T SUM(vector<T> vec){return accumulate(all(vec),(T)0);} // vectorの中身を全部足す
template<typename T>inline T digitSum(T num){T sum = 0;while(num){sum+=num%10;num/=10;}return sum;} // 各桁の和
template<typename T>inline T gcd(T a,T b){if(b == 0)return a;return gcd(b,a%b);} // 最大公約数
template<typename T>inline T lcm(T a, T b){T g = gcd(a,b);return a/g*b;} // 最小公倍数
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<typename T>inline void print(T&& x){cout<<setprecision(32)<<x<<endl;}
string to_oct(int n){string s;while(n){s = to_string(n%8) + s;n /= 8;}return s;}

int main(){
  #define int ll
  int n,c;cin>>n>>c;
  vector<pair<int,int>> a;
  rep(i,n){
    int _a,_b,_c;cin>>_a>>_b>>_c;
    a.push_back(make_pair(_a,_c));
    a.push_back(make_pair(_b+1,-_c));
  }
  sort(all(a));

  int crt_day = 0;
  ll ans = 0;
  ll sum = 0;
  for(int i = 0;i < a.size();i++){
    int days = a[i].fi - crt_day;
    if(i != 0 && a[i-1].fi != a[i].fi || i == a.size()-1){
      ans += min(sum, c) * days;
    }
    sum += a[i].se;
    crt_day = a[i].fi;
  }
  print(ans);
  return 0;
}


#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	int H,W,count;
	char a;
	count = 0;
	cin >> H >> W;
	vector<vector<char>> S(H, vector<char>(W));
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> S[i][j];
		}
	}
	for (int i = 0; i <= H-2; i++) {
		for (int j = 0; j <= W-2; j++) {
			a = S[i][j];
			if (a == '.') {
				if (a == S[i][j + 1]) {
					count += 1;
				}
				if (a == S[i + 1][j]) {
					count += 1;
				}
			}
		}
	}
	for (int i = 0; i <= H - 2; i++) {
		a = S[i][W-1];
		if (a == '.') {
			if (a == S[i + 1][W - 1]) {
				count += 1;
			}
		}
	}
	for (int i = 0; i <= W - 2; i++) {
		a = S[H-1][i];
		if (a == '.') {
			if (a == S[H - 1][i + 1]) {
				count += 1;
			}
		}
	}
	cout << count;
	return 0;
}

#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<map>
#include<vector>
#include<math.h>
#include<stdio.h>
#include<stack>
#include<queue>
#include<tuple>
#include<cassert>
#include<set>
#include<bitset>
#include<functional>
#include <fstream>
//#include<bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i, x) for(ll i = 0; i < x; i++)
#define rep2(i, x) for(ll i = 1; i <= x; i++)
#define all(a) (a).begin(),(a).end()
#define puts(x) cout << (x) << endl;
using ll = long long;
using ld = long double;
using namespace std;
const ll INF = 10000000000000000;
const int intINF = 1000000000;
const ll mod = 1000000007;
const ll MOD = 998244353;
const ld pi = 3.141592653589793238;

bool isprime(int p) {
	if (p == 1) return false;
	for (int i = 2; i < p; i++) {
		if (p % i == 0) return false;
	}
	return true;
}
ll gcd(ll a, ll b) {
	if (a < b)swap(a, b);
	if (a % b == 0)return b;
	return gcd(b, a % b);
}
ll lcm(ll a, ll b) {
	return a / gcd(a, b) * b;
}
ll keta(ll n) {
	ll res = 0;
	while (n >= 1) {
		res += n % 10; n /= 10;
	}
	return res;
}
ll modpow(ll x, ll y) {
	ll res = 1;
	while (y) {
		if (y % 2) { res *= x; res %= mod; }
		x = x * x % mod; y /= 2;
	}
	return res;
}
ll nCk(ll n, ll k) {
	ll a = 1, b = 1;
	for (int h = n - k + 1; h <= n; h++) { a *= h; a %= mod; }
	for (int h = 1; h <= k; h++) { b *= h; b %= mod; }
	return a * modpow(b, mod - 2) % mod;
}
//printf("%.10f\n", n);
typedef pair <ll, ll> P;
ll dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 };
struct edge { ll to, cost; };
struct status {
	ll cost;
	ll bango;

	bool operator<(const status& rhs) const { return cost < rhs.cost; };
	bool operator>(const status& rhs) const { return cost > rhs.cost; };
};

signed main() {
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	//cout << fixed << setprecision(15);

	//input
	ll n, m; cin >> n >> m;

	vector<P> a(n); vector<ll> mi(n + 1);
	rep(i, n) { cin >> a[i].first; a[i].second = i + 1; mi[i + 1] = a[i].first; }
	sort(all(a)); reverse(all(a));

	vector<ll> x(m), y(m);
	vector<vector<ll>> G(n + 2);
	rep(i, m) { cin >> x[i] >> y[i]; G[y[i]].push_back(x[i]); }

	vector<ll> ma(n + 2, 0 - INF);
	vector<bool> visit(n + 2);
	rep(i, a.size()) {
		queue<ll> que; ll cnt = a[i].first;
		if (!visit[a[i].second]) {
			que.push(a[i].second);
		}
		while (que.size()) {
			ll q = que.front(); que.pop();
			for (int i = 0; i < G[q].size(); i++) {
				if (!visit[G[q][i]]) {
					que.push(G[q][i]); visit[G[q][i]] = true;
					ma[G[q][i]] = cnt;
				}
			}
		}
	}
	ll ans = 0 - INF;
	rep2(i, n) {
		ans = max(ans, ma[i] - mi[i]);
	}
	cout << ans << endl;
	return 0;
}


#include <iostream>
#include <stack>
#include <string>
#include <vector>
#pragma warning(disable:4996)
using namespace std;
#define int long long
stack<int>way;
int N,M,K;
double ex[200100];
double ep[200100];
double epex[200100];
vector<pair<int, int>>x;
signed main()
{
	ios_base::sync_with_stdio(false);
	cin >> N>>M >> K;
	int i;
	for (i = 0; i < K; i++)
	{
		int a;
		cin >> a;
		ep[a] = 1;
	}
	for (i = N; i <= N + M; i++)
	{
		ex[i] = 0;
	}
	double curex = 0, curep = 0,expex=0;
	for (i = N - 1; i >= 0; i--)
	{
		int isb = ep[i] >= 0.99999999;
		if (isb)
			goto T;
		ep[i] = curep;

		if (ep[i] <=0.999999999)
		{
			ex[i] = ((curex))/(M-curep*M)+1;
			if(curep>0)
				epex[i] = expex / (curep*M)+1;
		}
		else
		{
			if (!isb)
			{
				if (curep > 0)
					epex[i] = expex / (curep*M) + 1;
			}
		}
		T:
		curex -= ex[i + M]*(1-ep[i+M]);
		curep -= ep[i + M]/M;
		expex -= epex[i + M]*ep[i+M];
		curex += ex[i]*(1-ep[i]);
		curep += ep[i]/M;
		expex += epex[i]*ep[i];
	}
	i = 0;
	if (ep[i] >= 0.99999999)
		cout << -1;
	else
	{
		cout << ((1 - ep[i]) * ex[i] +epex[i]*ep[i]) / (1 - ep[i]);
	}
}

#include <bits/stdc++.h>
using namespace std;
//#include <atcoder/all>
//using namespace atcoder;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rep1(i,n) for (int i = 1; i <= (n); ++i)
#define bit(n,k) ((n>>k)&1) //nのk　bit目
#define vec(T) vector<T>
#define vvec(T) vector<vector<T>>
using ll = long long;
using P = pair<int,int>;

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const ll llINF = 1LL << 60;
const int iINF = 1e9;

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

using Pd = pair<double,double>;

struct Solver{

    Pd add(Pd a,Pd b){
        a.first += b.first;
        a.second += b.second;
        return a;
    }

    Pd sub(Pd a,Pd b){
        a.first -= b.first;
        a.second -= b.second;
        return a;
    }

    Pd div(Pd a,int m){
        a.first /= m;
        a.second /= m;
        return a;
    }

    void solve(){
        int N,M,K;
        cin >> N >> M >> K;

        vec(Pd) dp(N+M+10);
        vec(int) st(N);

        int cnt=0;
        int pre,now;
        pre=-1;
        rep(ki,K){
            cin >> now;
            if(now==pre+1) cnt++;
            else cnt=0;
            if(cnt==M-1){
                cout << -1 << endl;
                return;
            }
            st[now] = 1;
            pre = now;
        }

        Pd csum = {0,0};

        for(int i = N-1; i>=0; i--){
            csum = add(csum,dp[i+1]);
            csum = sub(csum,dp[i+M+1]);

            if(st[i]){
                dp[i].first = 1.0;
            }else{
                dp[i] = div(csum,M);
                dp[i].second += 1.0;
            }
        }
        double ans;
        ans = dp[0].second/(1.0-dp[0].first);

        printf("%6.4f\r\n",ans);

    }
};

int main(){
    int testcasenum=1;
    //cin >> testcasenum;
    rep1(ti,testcasenum){
        Solver solver;
        solver.solve();
    }
    return 0;
}


//#pragma GCC optimize ("O2")
//#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
//#include<atcoder/all>
//using namespace atcoder;

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

//おそそう

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	if ((tmp & ma0) ^ ma0) {
		int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
		tmp = tmp << dig & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += (72 - dig >> 3);
	}
	else {
		tmp = tmp & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += 8;
		if (*ci++ == '0') {
			tmp = tmp * 10;
			ci++;
		}
	}
	return tmp;
}
void pakuri_sort(int N, ll A[]) {
	const int b = 8;
	ll tmp[100001];
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}
ll li[300];
int li2[300];

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint(), M = getint();
	int w[8];
	rep(i, N) w[i] = getint();

	ll lv[100001];
	rep(i, M) {
		ll l = getint();
		int v = getint();
		lv[i] = l << 32 | v;
	}
	pakuri_sort(M, lv);
	lv[M] = 1000000001ll;

	rep(i, 1 << N) {
		rep(j, N) if (i >> j & 1) li[i] += w[j];
		li[i] = li[i] << 30 | i;
	}
	sort(li, li + (1 << N));
	int saidai = 0;
	int k = 0;
	rep(i, 1 << N) {
		while ((lv[k] & (1 << 30) - 1) < li[i] >> 30) {
			if (saidai < lv[k] >> 32) saidai = lv[k] >> 32;
			k++;
		}
		li[i] = ll(saidai) << 30 | (li[i] & (1 << 30) - 1);
	}
	rep(i, 1 << N) li2[li[i] & (1 << 30) - 1] = li[i] >> 30;

	rep(i, N) {
		if (w[i] > (lv[0] & (1 << 30) - 1)) {
			printf("-1");
			return 0;
		}
	}
	int P[8];
	rep(i, N) P[i] = i;

	int kotae = 1e9;
	do {
		int tmp[8] = {};
		rep(p, N - 1) {
			int omosa = 1 << P[p];
			for (int q = p + 1; q < N; q++) {
				omosa |= 1 << P[q];
				int kari = tmp[p] + li2[omosa];
				if (tmp[q] < kari) tmp[q] = kari;
			}
		}
		if (kotae > tmp[N - 1]) kotae = tmp[N - 1];

	} while (next_permutation(P, P + N));

	printf("%d\n", kotae);

	Would you please return 0;
}

#include<bits/stdc++.h>
#define int long long
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,abm,mmx,avx,avx2")
#pragma GCC optimize("unroll-loops")
#define ri register signed
#define rd(x) x=read()
using namespace std;
const int N=2e5+5;
const int maxn=5e6+5;
const int mod=998244353;
inline int read(){int x=0,f=1;char ch=getchar();while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline int ksm(int x,int y,int z){int ret=1;while (y){if (y&1) ret=(ret*x)%z;x=(x*x)%z;y>>=1;}return ret;}
int inv[maxn],fac[maxn],ifc[maxn];
void Init(int n)
{
    inv[1]=1;for (ri i=2;i<=n;i++)inv[i]=inv[mod%i]*(mod-mod/i)%mod;
    fac[0]=1;for (ri i=1;i<=n;i++) fac[i]=fac[i-1]*i%mod;
    ifc[0]=1;for (ri i=1;i<=n;i++) ifc[i]=ifc[i-1]*inv[i]%mod;
}
int C(int n,int m){if (m>n || m<0) return 0;return fac[n]*ifc[m]%mod*ifc[n-m]%mod;}

int n,k,ans,res;
vector<int> T[N];
int dep[N];
void dfs(int u,int fa,int lim)
{
	for (int v:T[u]) if (v!=fa) dfs(v,u,lim);
	if (u!=1)
	{
		if (T[u].size()==1) dep[u]=0;
		else
		{
			dep[u]=-n;
			int mn=n,mx=-n;
			for (int v:T[u]) if (v!=fa) mx=max(mx,dep[v]+1),mn=min(mn,dep[v]+1);
			if (mx+mn<0) dep[u]=mn;
			else dep[u]=mx;
			if (dep[u]==lim) {res++;dep[u]=-lim-1;}
		}
	}
	else
	{
		int mn=n,mx=-n;
		for (int v:T[u]) mx=max(mx,dep[v]+1),mn=min(mn,dep[v]+1);
		if (mx+mn<0) dep[u]=mn;
		else dep[u]=mx;
		if (dep[u]>=0) res++;
	}
}
bool chk(int x)
{
	res=0;
	for (int i=1;i<=n;i++) dep[i]=0;
	dfs(1,0,x);
	return res<=k;
}
signed main()
{
	rd(n);rd(k);
	if (k==n) {puts("0");return 0;}
	for (int i=1,x,y;i<n;i++) rd(x),rd(y),T[x].push_back(y),T[y].push_back(x);
	int l=1,r=n;
	while (l<=r)
	{
		int mid=(l+r)/2;
		if (chk(mid)) ans=mid,r=mid-1;
		else l=mid+1;
	}
	cout<<ans<<endl;
}


#pragma GCC optimize("Ofast")
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <cctype>
#include <sstream>
#include <stack>
#include <deque>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <unordered_map>

using namespace std;

using ll = long long;
using P = pair<ll, ll>;
using Po = pair<double, double>;
template <class T>
using V = vector<T>;
template <class T>
using VV = V<V<T>>;

#define REP(i,n) for(ll i=0;i<ll(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=ll(a);i<=ll(b);i++)
#define FORD(i,a,b) for(ll i=ll(a);i>=ll(b);i--)
#define PB push_back
#define MP make_pair
#define SZ(x) ll(x.size())
#define ALL(x) x.begin(),x.end()
#define NIL -1
#define INF pow(2,31)-1
#define MOD 1000000007
#define PI 3.14159265358979323846
#define endl "\n"
#define EPS 1e-9

template <class T, class U>
bool chmin(T& t, const U& u) {
	if (t > u) {
		t = u;
		return true;
	}
	else return false;
}
template <class T, class U>
bool chmax(T& t, const U& u) {
	if (t < u) {
		t = u;
		return true;
	}
	else return false;
}

ll powmod(ll x, ll n, ll mod) {
	ll s = 1;
	REP(i, n) {
		s = s * x % mod;
	}
	if (s < 0)s += mod;
	return s;
}

signed main() {
	ll n;
	cin >> n;
	V<ll> a(n), b(n);
	REP(i, n)cin >> a[i];
	REP(i, n)cin >> b[i];
	ll c = 0;
	REP(i, n) {
		c += a[i] * b[i];
	}
	c ? cout << "No" << endl : cout << "Yes" << endl;
}

#include <bits/stdc++.h>

using namespace std;

int main()
{
    long long n;
    cin >>n;
    vector <long long> a(n), b(n);
    for (int i = 0; i < n; ++i) {
        cin >>a[i];
    }
    for (int i = 0; i < n; ++i) {
        cin >>b[i];
    }
    long long res = 0;
    for (int i = 0; i < n; ++i) {
        long long cur = a[i] * b[i];
        res += cur;
    }
    if (res == 0) {
        cout <<"Yes"<<endl;
    }
    else {
        cout <<"No"<<endl;
    }
}


#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
#include<vector>
#include<algorithm>
#include<utility>

using namespace std;

#define int long long
#define endl "\n"

constexpr long long INF = (long long)1e18;
constexpr long long MOD = 1'000'000'007;

struct fast_io {
	fast_io(){
		std::cin.tie(nullptr);
		std::ios::sync_with_stdio(false);
	};
} fio;

signed main(){
	cout<<fixed<<setprecision(10);

	int A, B;
	vector<int> num;
	vector<vector<int>> dp;
	vector<int> p;
	int ans = 0;
	int n;

	cin>>A>>B;

	for(int i = 2; i <= B - A; i++){
		bool flag = false;

		for(int j = 2; j * j <= i; j++){
			if(i%j == 0) {
				flag = true;
				break;
			}
		}

		if(!flag) p.push_back(i);
	}

	n = p.size();

	num.resize(B - A + 1);
	dp.resize(B - A + 2, vector<int>(1<<n));

	for(int i = A; i <= B; i++){
		int bit = 0;
		for(int j = 0; j < n; j++){
			if(i%p[j] == 0) {
				bit |= (1<<j);

			}
		}
		num[i-A] = bit;
	}

	dp[0][0] = 1;

	for(int i = A; i <= B; i++){
		for(int j = 0; j < 1<<n; j++){
			if(!(num[i-A]&j)) dp[i-A+1][num[i-A]|j] += dp[i-A][j];
				dp[i-A+1][j] += dp[i-A][j];
		}
	}

	for(int j = 0; j < 1<<n; j++){
		ans += dp[B - A + 1][j];
	}

	cout<<ans<<endl;

	return 0;
}

#include <bits/stdc++.h>
#define ff first
#define ss second
#define endl '\n'
using namespace std;
const long long INF = (long long) 1e18;
const int mod = (int) 1e9+7;
const int MAXN = (int) 3e5+5;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll n, t;
ll a[MAXN];

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

    #ifdef Local
        freopen("C:/Users/Admin/Desktop/Yazilim/C/IO/int.txt","r",stdin);
        freopen("C:/Users/Admin/Desktop/Yazilim/C/IO/out.txt","w",stdout);
    #endif

    cin>>n>>t;

  	for(int i = 0; i < n; i++)
      	cin>>a[i];

 	int m = n / 2;
  	vector<int> vc;
  	int ans = 0;
  	for(int i = 0; i < (1<<m); i++){
        ll top = 0;
    	for(int j = 0; j < m; j++){
         	if((1<<j) & i)
              	top += a[j];
        }
      	if(top > t) continue;

      	vc.push_back(top);
        ans = max(ans,(int) top);
    }

  	sort(vc.begin(), vc.end());

	int len = (n - m);

    for(int i = 0; i < (1<<len); i++){
    	ll top = 0;
		for(int j = 0; j < len; j++){
        	if((1<<j) & i)
              top += a[m + j];
        }

      	if(top > t) continue;
      	ans = max(ans,(int) top);
      	int ot = upper_bound(vc.begin(), vc.end(), t - top) - vc.begin();
        //cout<<top<<" "<<vc[ot - 1]<<endl;
      	if(ot != 0)
          	ans = max(ans, (int)top + vc[ot - 1]);
    }

  	cout<<ans<<endl;

    #ifdef Local
        cout<<endl<<fixed<<setprecision(2)<<1000.0 * clock() / CLOCKS_PER_SEC<< " milliseconds ";
    #endif
}


/*** author: yuji9511 ***/
#include <bits/stdc++.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using ll = long long;
using lpair = pair<ll, ll>;
using vll = vector<ll>;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define rep(i,m,n) for(ll i=(m);i<(n);i++)
#define rrep(i,m,n) for(ll i=(m);i>=(n);i--)
ostream& operator<<(ostream& os, lpair& h){ os << "(" << h.first << ", " << h.second << ")"; return os;}
#define printa(x,n) for(ll i=0;i<n;i++){cout<<(x[i])<<" \n"[i==n-1];};
void print() {}
template <class H,class... T>
void print(H&& h, T&&... t){cout<<h<<" \n"[sizeof...(t)==0];print(forward<T>(t)...);}

void solve(){
    ll N,C;
    cin >> N >> C;
    vll a(N),b(N),c(N);
    rep(i,0,N) cin >> a[i] >> b[i] >> c[i];
    typedef struct {
        ll pos;
        ll val;
        ll t;
    } P;
    vector<P> v;
    rep(i,0,N){
        v.push_back({a[i], c[i], 0});
        v.push_back({b[i]+1, c[i], 1});
    }
    sort(v.begin(), v.end(),[](P p1, P p2){
        if(p1.pos == p2.pos){
            return p1.t < p2.t;
        }
        return p1.pos < p2.pos;
    });

    ll ans = 0;
    ll sum = 0;
    ll prev_pos = -1;
    for(auto &e: v){
        if(prev_pos != -1){
            if(sum <= C){
                ans += sum * (e.pos - prev_pos);
            }else{
                ans += C * (e.pos - prev_pos);
            }
        }
        if(e.t == 0){
            sum += e.val;
        }else{
            sum -= e.val;
        }
        prev_pos = e.pos;
    }
    print(ans);

}

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    solve();
}

/* Hardwork allways pays off */
//You never know how close to the solution you are ,so keep practicing
#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less
#include <iostream>
using namespace __gnu_pbds;
using namespace std;

#define int long long

#define ld long double
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#define endl '\n'
#define REP(i,n) for(int i=1;i<=n;i++)
#define tol(s) transform(s.begin(),s.end(),s.begin(),::tolower)
#define tou(s) transform(s.begin(),s.end(),s.begin(),::toupper)
#define ios ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(x) (x).begin(), (x).end()
#define mod1 998244353
#define mod 1000000007
#define pie 3.141592653589793238
#define printv(x) for(i=0;i<x.size();i++) cout<<x[i]<<" ";
#define printA(x,n) for(i=0;i<n;i++) cout<<x[i]<<" ";
#define F first
#define S second
#define vi vector<int>
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> new_data_set;

void make_unique(vector<int> vec)
{
sort(all(vec));
vec.resize(unique(all(vec)) - vec.begin());
}

bool isPowerOfTwo(int n)
{
   if(n==0)
   return false;

   return (ceil(log2(n)) == floor(log2(n)));
}
int cceil(int x, int y){
    return (x+y-1)/y;
}
struct Cmp
{
        bool operater(const pair<int,int> &a,const pair<int,int> &b)
       {
               return (a.second)<(b.second);
       }

};
bool cmp(const pair<int,int> &a,const pair<int,int> &b)
{
       return (a.second)<(b.second);
}

signed main()
 {   ios;
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    // cout.precision(1);
    // cout<<fixed;
    int t=1;
    // init();
      // cin>>t;
    while(t--)
    {
        int n,x,i,j,flag=0,count=0,sum=0;
        int v,ti,s,d;
        cin>>v>>ti>>s>>d;
        if(ti*v<=d&&s*v>=d)
          cout<<"No"<<endl;
        else
          cout<<"Yes"<<endl;

    }
    return 0;

}


#include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(int)(n);i++)
using namespace std;
using P=pair<int,int>;

int main(){
  double x,y,z;
  cin>>x>>y>>z;
  cout<<floor((y*z-1)/x)<<endl;
}

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

int main(){
    double X, Y, Z, v, a, b;
    cin >> X >> Y >> Z;
    v = Y / X;
    a = Z * v;
    long long int d = a;
    if(d == a){
        cout << d-1 << endl;
    }else{
        cout << d << endl;
    }
    return 0;
}


// #define _GLIBCXX_DEBUG // for STL debug (optional)
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
#include <bitset>
using namespace std;
using ll = long long int;
using int64 = long long int;

template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}

int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int INF = 1LL << 29;
const ll LONGINF = 1LL << 60;
const ll MOD = 1000000007LL;

int main() {
    int N; cin >> N;
    string s; cin >> s;

    if(s.front() != s.back()) {
        cout << 1 << endl;
        return 0;
    }
    else {
        char c = s.front();
        for(int i=0; i+1<N; i++) {
            if(s[i] != c and s[i+1] != c) {
                cout << 2 << endl;
                return 0;
            }
        }
        cout << -1 << endl;
        return 0;
    }
    return 0;
}

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

template<typename T>
void view_1d(vector<T> V, string sep) {
    for (ll i=0; i<V.size(); i++) {
        cout << V[i];
        if (i == V.size() - 1) {
            cout << endl;
        } else {
            cout << sep;
        }
    }
}

template<typename T>
void view_2d(vector<vector<T>> V, string sep) {
    for (ll i=0; i<V.size(); i++) {
        for (ll j=0; j<V[i].size(); j++) {
            cout << V[i][j];
            if (j == V[i].size() - 1) {
                cout << endl;
            } else {
                cout << sep;
            }
        }
    }
}

//==============================//

int main() {
    int N;
    string S, T;
    cin >> N >> S >> T;

    int tmp = 0;
    for (int i=0; i<N; i++) {
        tmp += (S[i] - '0') - (T[i] - '0');
    }

    int ans = 0;
    if (tmp == 0) {
        vector<int> cnt_S, cnt_T;
        for (int i=0; i<N; i++) {
            if (S[i] == '0') cnt_S.push_back(i);
            if (T[i] == '0') cnt_T.push_back(i);
        }
        for (int j=0; j<cnt_S.size(); j++) {
            if (cnt_S[j] != cnt_T[j]) ans++;
        }
    } else {
        ans = -1;
    }

    cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define f(i,a,n) for(ll i=a;i<n;i++)
#define w(x) ll _t;cin>>_t;f(x,1,_t+1)
#define br cout<<"\n"

ll mod=1e9+7;
template<class T>
void printArr(T arr,int n){
    cout<<"\n[";f(i,0,n) cout<<arr[i]<<", ";
    cout<<"]\n";
}
ll gcd(ll a,ll b){
    if(b == 0) return a;
    return gcd(b,a%b);
}

ll lcm(ll a,ll b){
    return (a*b)/gcd(a,b);
}

ll poww(ll a,ll m){
    ll res=1;
    a = a%mod;
    for(;m;m>>=1){
        if(m&1){
            res=(res*a)%mod;
        }
        a=(a*a)%mod;
    }
    return res;
}

bool cmp(pair<int,int> &a,pair<int,int> &b){
    return a.second>=b.second;
}

/*int lpf[1000001];

void createLPF(){
    f(i,0,1000001) lpf[i]=INT_MAX;
    lpf[1]=1;
    for(int i=2;i*i<=1000000;i++){
        if(lpf[i]==INT_MAX){
            lpf[i] = i;
            for(int j=2*i;j<=1000000;j+=i) lpf[j] = min(lpf[j],i);
        }
    }
}*/

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

    //w(_x)//testcases
    {
        ll n;cin>>n;
        ll a[1<<n];
        f(i,0,1<<n) cin>>a[i];

        vector<int> notlost;
        f(i,0,1<<n) notlost.push_back(i);
        ll ans = -1;
        for(int i=0;i<n;i++){
            vector<int> newin;
            for(int j=0;j<notlost.size()-1;j+=2){
                int p1=notlost[j],p2=notlost[j+1];
                if(a[p1]>a[p2]) {newin.push_back(p1);ans = p2;}
                else {newin.push_back(p2);ans = p1;}
            }
            notlost = newin;
        }
        cout<<ans+1;

    }
    return 0;
}

// This code wrote by chtholly_micromaker(MicroMaker)
#include <bits/stdc++.h>
#define reg register
#define int long long
#define ALL(x) (x).begin(),(x).end()
#define mem(x,y) memset(x,y,sizeof x)
#define sz(x) (int)(x).size()
#define ln std::puts("")
#define lsp std::putchar(32)
#define pb push_back
#define MP std::make_pair
#define dbg(x) std::cerr<<__func__<<"\tLine:"<<__LINE__<<' '<<#x<<": "<<x<<"\n"
#define dprintf(x...) std::fprintf(stderr,x)
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define per(i,b,a) for(int i=(b);i>=(a);--i)
template <class t> inline void read(t &s){s=0;
reg int f=1;reg char c=getchar();while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c))s=(s<<3)+(s<<1)+(c^48),c=getchar();s*=f;return;}
template<class t,class ...A> inline void read(t &x,A &...a){read(x);read(a...);}
template <class t> inline void write(t x){if(x<0)putchar('-'),x=-x;
int buf[21],top=0;while(x)buf[++top]=x%10,x/=10;if(!top)buf[++top]=0;
while(top)putchar(buf[top--]^'0');return;}
inline void setIn(std::string s){freopen(s.c_str(),"r",stdin);return;}
inline void setOut(std::string s){freopen(s.c_str(),"w",stdout);return;}
inline void setIO(std::string s=""){setIn(s+".in");setOut(s+".out");return;}
template <class t>inline bool checkmin(t&x,t y){if(x>y){x=y;return 1;}return 0;}
template <class t>inline bool checkmax(t&x,t y){if(x<y){x=y;return 1;}return 0;}
inline int lowbit(int x){return x&(-x);}
int a[1<<16|5],loser;
inline int dfs(int l,int r)
{
	if(l==r)
		return read(a[l]),a[l];
	reg int mid=(l+r)>>1,L=dfs(l,mid),R=dfs(mid+1,r);
	loser=std::min(L,R);
	return std::max(L,R);
}
signed main(void)
{
	int n;read(n);
	dfs(1,1<<n);
	for(int i=1;i<=(1<<n);++i)
		if(loser==a[i])
			write(i),ln;
	return 0;
}

/*
 * Check List:
 * 1. Input / Output File (OI)
 * 2. long long
 * 3. Special Test such as n=1
 * 4. Array Size
 * 5. Memory Limit (OI) int is 4 and longlong is 8
 * 6. Mod (a*b%p*c%p not a*b*c%p  ,  (a-b+p)%p not a-b )
 * 7. Name ( int k; for(int k...))
 * 8. more tests , (T=2 .. more)
 * 9. blank \n after a case
*/


#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <cctype>
#include <cmath>
#include<deque>
#include<map>
#include<algorithm>
#include<iomanip>
#include<numeric>
using namespace std;

#define rep(i,n) for(int i = 0; i < n; i++)
#define rep1(i,begin,end) for(int i = begin; i < end; i++)
#define all(c) c.begin(), c.end()
#define ll long long
#define INF 2e9
#define LINF 9223372036854775807
#define cout(n) cout << fixed << setprecision(n)
#define pii pair<int,int>
#define pll pair<long long,long long>
#define mod 1000000007;

template<typename T>pair<T, T> max_idx(vector<T>& a) { T ans = 0; T index = 0; for (int i = 0; i < a.size(); i++) { if (a[i] > ans) { ans = a[i]; index = i; } }pair<T, T> ret = { ans,index }; return ret; }
template<typename T>pair<T, T> min_idx(vector<T>& a) { T ans = INF; T index = 0; for (int i = 0; i < a.size(); i++) { if (a[i] < ans) { ans = a[i]; index = i; } }pair<T, T> ret = { ans, index }; return ret; }
long long Factorial(int n) { ll sum = 1; for (int i = n; i > 0; i--) { sum *= i; }return sum; }

int main() {
	int a, b, c;
	cin >> a >> b >> c;
	vector<int> d(3);
	d[0] = a;
	d[1] = b;
	d[2] = c;
	sort(all(d));
	reverse(all(d));
	cout << d[0] + d[1] << endl;
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define deb(x) cout << #x << " " << x << endl;
#define mod 1000000007
#define fast std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define endl "\n"

const ll INF = 1e18;
const ll NEGINF = -1 * INF;

/*NOTES: Take care of ll vs int
         Never use an iterator after erasing it
*/

void solve()
{
    vector<int> a(3);
    for (int i = 0; i < 3; i++)
    {
        cin >> a[i];
    }
    sort(a.begin(), a.end());
    cout << a[1] + a[2] << endl;
}

int main()
{
    fast;
#ifndef ONLINE_JUDGE
    freopen("/home/kalit/Desktop/Data Structures-Algo-Competitive/src/codeforces/input.txt", "r", stdin);
    freopen("/home/kalit/Desktop/Data Structures-Algo-Competitive/src/codeforces/output.txt", "w", stdout);
#endif
    int T = 1;
    while (T--)
    {
        solve();
    }
    //cout<< "Done in " << clock() / CLOCKS_PER_SEC <<"sec"<< endl;
    return 0;
}


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

int main(){
    ll N;cin>>N;
    vector<ll> A(N);
    for(ll i=0;i<N;i++){
        cin>>A[i];
    }
    ll ans=0;
    sort(A.rbegin(), A.rend());
    for(ll i=0; i<N; i++){
        ans += A[i]*(N-1-i) - A[i]*i;
    }
    cout << ans << endl;

}

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

int main(){

    int N;

  	cin >> N;

  	vector<int> A(N),B(N),C(N);

    for (int i = 1; i <= N; ++i) cin >> A[i];
   	for (int i = 1; i <= N; ++i) cin >> B[i];
  	for (int i = 1; i <= N; ++i) cin >> C[i];

  	vector<int> count(N);
  	for(int j = 1; j <= N; ++j) count[B[C[j]]] += 1;

  	long long num = 0;
  	for(int i = 1; i <= N; ++i) num += count[A[i]];

    cout << num << endl;
}


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

int main() {
  int N;
  long long int X;
  cin >> N >> X;
  vector<int> A(N);
  for (int i = 0; i < N; i++) cin >> A.at(i);

  long long int ans = 2000000000000000000;
  for (int C = 1; C <= N; C++) {
    int MOD = X % C;
    vector<vector<vector<long long int>>> DP(N + 1, vector<vector<long long int>>(C + 1, vector<long long int>(C, -1)));
    DP.at(0).at(0).at(0) = 0;
    for (int i = 1; i <= N; i++) {
      for (int j = 0; j <= C; j++) {
        for (int k = 0; k < C; k++) {
          if (DP.at(i - 1).at(j).at(k) != -1) DP.at(i).at(j).at(k) = DP.at(i - 1).at(j).at(k);
          int kk = k - (A.at(i - 1) % C);
          if (kk < 0) kk += C;
          if (j > 0 && DP.at(i - 1).at(j - 1).at(kk) != -1) DP.at(i).at(j).at(k) = max(DP.at(i).at(j).at(k), DP.at(i - 1).at(j - 1).at(kk) + A.at(i - 1));
        }
      }
    }
    if (DP.at(N).at(C).at(MOD) > 0) ans = min(ans, (X - DP.at(N).at(C).at(MOD)) / C);
  }
  cout << ans << endl;
}

//#define _DEBUG
#include "bits/stdc++.h"
//#include <atcoder/all>
#define CHOOSE(a) CHOOSE2 a
#define CHOOSE2(a0,a1,a2,a3,a4,a5,x,...) x
#define debug_1(x1) cout<<#x1<<": "<<x1<<endl
#define debug_2(x1,x2) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<endl
#define debug_3(x1,x2,x3) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<endl
#define debug_4(x1,x2,x3,x4) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<endl
#define debug_5(x1,x2,x3,x4,x5) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<", "#x5<<": "<<x5<<endl
#define debug_6(x1,x2,x3,x4,x5,x6) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<", "#x5<<": "<<x5<<", "#x6<<": "<<x6<<endl
#ifdef _DEBUG
#define debug(...) CHOOSE((__VA_ARGS__,debug_6,debug_5,debug_4,debug_3,debug_2,debug_1,~))(__VA_ARGS__)
#else
#define debug(...)
#endif
#define rep(index,num) for(int index=0;index<(int)num;index++)
#define rep1(index,num) for(int index=1;index<=(int)num;index++)
#define brep(index,num) for(int index=(int)num-1;index>=0;index--)
#define brep1(index,num) for(int index=(int)num;index>0;index--)
#define scan(argument) cin>>argument
#define prin(argument) cout<<argument<<endl
#define kaigyo cout<<endl
#define eps 1e-7
#define mp(a1,a2) make_pair(a1,a2)
#define ALL(a) (a).begin(),(a).end()
#define rALL(a) (a).rbegin(),(a).rend()
#define puba(a) emplace_back(a)
#define pubamp(a,b) emplace_back(mp(a,b))
typedef long long ll;
typedef long double ld;
using namespace std;
//using namespace atcoder;
typedef pair<ll,ll> pll;
typedef pair<int,int> pint;
typedef vector<int> vint;
typedef vector<ll> vll;
typedef vector<pint> vpint;
typedef vector<pll> vpll;
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
ll INFl=(ll)1e+18+1;
int INF=1e+9+1;
int main(){
	int N;
	ll X,A[101];
	scan(N>>X);
	rep(i,N) scan(A[i]);
	ll ans=INFl;
	rep1(chkosu,N){
		ll dp[101][101][100]={};//dp[i][j][mod]:i個目まで見てj個選んでいて魔力の総和%chkosuがmodであるような魔力の最大値
		rep(i,N+1) rep(j,chkosu+1) rep(mod,chkosu) dp[i][j][mod]=-INFl;
		dp[0][0][0]=0;
		rep(i,N){
			rep(j,chkosu+1){
				rep(mod,chkosu){
					if(j<chkosu) chmax(dp[i+1][j+1][(mod+A[i])%chkosu],dp[i][j][mod]+A[i]);
					chmax(dp[i+1][j][mod],dp[i][j][mod]);
				}
			}
		}
		ll canReachMaryokuMax=dp[N][chkosu][X%chkosu];
		debug(chkosu,canReachMaryokuMax,X%chkosu,(X-canReachMaryokuMax)/chkosu);
		if(canReachMaryokuMax<=0) continue;
		assert(canReachMaryokuMax<=X);
		chmin(ans,(X-canReachMaryokuMax)/chkosu);
	}
	prin(ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
const int inf = 1e9;

int a[maxn], b[maxn];

int main(){
	ios_base::sync_with_stdio(false);
	int n, L;
	cin >> n >> L;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	a[0] = 0, a[n+1] = L+1;
	for (int i = 1; i <= n; i++)
		cin >> b[i];
	b[0] = 0, b[n+1] = L+1;
	int last = 1;
	ll answer = 0;
	set<pair<int,int>> S, T;
	for (int i = 0; i <= n+1; i++){
		S.insert({a[i]-i,-i});
		T.insert({a[i]-i,+i});
	}
	for (int i = 1; i <= n+1; i++){
		if (a[i] > b[i]){
			if (b[i-1]+1 == b[i]){
				answer ++;
				continue;
			}
			auto it = S.lower_bound({b[i]-i,-inf});
			if ((*it).first != b[i]-i)
				return cout << "-1\n", 0;
			answer += i+(*it).second;
		}
		if (a[i] < b[i]){
			if (b[i]+1 == b[i+1]){
				answer ++;
				continue;
			}
			auto it = T.lower_bound({b[i]-i,-inf});
			if ((*it).first != b[i]-i)
				return cout << "-1\n", 0;
			answer += (*it).second-i;
		}
	}
	cout << answer << '\n';
}

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define rrep(i,n) RREP(i,(n)-1,0)
#define all(v) v.begin(), v.end()
#define endk '\n'
const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;
const ll mod2 = 998244353;
const ld eps = 1e-10;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b){if(a>b) a=b;}
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b){if(a<b) a=b;}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int a, b; cin >> a >> b;
  int ans = 0;
  for(int i=1; i<=b-a+1; i++) {
    int _a = (a+i-1)/i, _b = b/i;
    if(_b-_a+1 >= 2) {
      chmax(ans, i);
    }
  }
  cout << ans << endk;
  return 0;
}


#include<bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#define endl "\n"
#define pb push_back
#define ll long long
#define d1(x)  cerr << #x << "--> " << x << endl
#define d2(x,y)  cerr << #x << "--> " << x << " | " << #y << "--> " << y <<endl
#define d3(x,y,z)  cerr << #x << "--> " << x << " | " << #y << "--> " << y <<" | " << #z << "--> "<< z<< endl
#define d4(x,y,z,w)  cerr << #x << "--> " << x << " | " << #y << "--> " << y <<" | " << #z << "--> "<< z << " | "<< #w << "--> " << w <<endl
#define vpll vector<pair<ll,ll>>
#define F first
#define S second
using namespace std;
ll mode = 1e9 + 7;
const ll maxn = 2*1e5 + 5;
const ll inf = 10000000000000;
ll __lcm(ll a, ll b){ return (a*b)/__gcd(a,b); }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll getRand(ll l, ll r){ uniform_int_distribution<int> uid(l, r); return uid(rng); }
template <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) { return out << "(" << a.F << ", " << a.S << ")"; }
template <class A> ostream& operator << (ostream& out, const vector<A> &v) {
out << "["; for (int i=0;i<v.size();i++) { if(i) out << ", "; out << v[i]; } return out << "]"; }

void solve(){

	ll n,C;
	cin>>n>>C;

	map<ll,ll> mp;
	for (int i=0;i<n;i++){
		ll a,b,c;
		cin>>a>>b>>c;
		mp[a]+=c;
		mp[b+1]-=c;
	}

	ll cur_sum = 0, ans = 0;
	pair<ll,ll> prev = {-1, -1};
	for (auto i:mp){
		if (prev.F==-1){
			prev = i;
			continue;
		}

		ll days = (i.F - prev.F);
		cur_sum += prev.S;

		ans += min( cur_sum, C )*days;
		prev = i;

	}

	cout<<ans<<endl;

	return;

}

int main(){

    #ifndef ONLINE_JUDGE
//		freopen("input.txt", "r", stdin);
//		freopen("output.txt", "w", stdout);
    #endif
    srand(time(0));

    ios::sync_with_stdio(0);
    cin.tie(0);

	ll test_case = 1;
	//cin>>test_case;
	while(test_case--) solve();

	return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

template <class T>
bool chmin(T &a, const T &b) {
  if (a <= b) return false;
  a = b;
  return true;
}
template <class T>
bool chmax(T &a, const T &b) {
  if (a >= b) return false;
  a = b;
  return true;
}

template <class T>
using MaxHeap = priority_queue<T>;
template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

void solve() {
  int N, X;
  cin >> N >> X;
  vector<int> A(N);
  cin >> A;

  vector<int> ans;
  for (int v : A)
    if (v != X) ans.push_back(v);

  for (int i = 0; i < ans.size(); i++) {
    cout << ans[i];
    if (i + 1 < ans.size())
      cout << ' ';
    else
      cout << endl;
  }

  return;
}

int main() {
  fastio();
  solve();
  // int t; cin >> t; while(t--)solve();

  // int t; cin >> t;
  // for(int i=1;i<=t;i++){
  //   cout << "Case #" << i << ": ";
  //   solve();
  // }
  return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
#include <map>
#include <bitset>
#include <cmath>
#include <functional>

using namespace std;

#define REP(i,n) for(ll (i) = (0);(i) < (n);++i)
#define REV(i,n) for(ll (i) = (n) - 1;(i) >= 0;--i)
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define FI first
#define SE second
#define ALL(v) v.begin(),v.end()
#define Decimal fixed<<setprecision(20)
#define INF 1000000000
#define LLINF 1000000000000000000LL
#define MOD 1000000007LL

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

template<typename T>
void show_vector(vector<T> v) {
	for (auto ele: v)cout << ele << " " ;cout << endl;
}

template<typename T>
void show_vector(vector<vector<T>> v) {
	for (auto ele: v)show_vector(ele);
}

template<typename T>
void show_vector(vector<vector<vector<T>>> v) {
	for (auto ele: v) {
		show_vector(ele);
		cout << endl;
	}
}

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

	ll n, m;cin >> n >> m;
	map<int, int> mp;
	REP(i, n) {
		ll a;cin >> a;mp[a]++;
	}
	REP(i, m) {
		ll b;cin >> b;mp[b]++;
	}

	for(auto ele: mp) {
		if(ele.SE == 1)cout << ele.FI << " ";
	}
	cout << endl;

	return 0;
}

//~ while (clock()<=69*CLOCKS_PER_SEC)
//~ #pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("O3")
//~ #pragma GCC target ("avx2")
//~ #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 __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set =
    tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
  ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
  *this << "[";
  for (auto it = d.b; it != d.e; ++it)
    *this << ", " + 2 * (it == d.b) << *it;
  ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

#define shandom_ruffle random_shuffle

using ll=long long;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
using vi=vector<int>;
using vll=vector<ll>;
const int nax=1000*1007;

int n;
char wcz[nax];

int main()
{
	scanf("%d", &n);
	scanf("%s", wcz+1);
	int row=1;
	for (int i=1; i<=n; i++)
	{
		if (wcz[i]!=wcz[1])
			row=0;
	}
	int wyn=nax;
	if (wcz[1]!=wcz[n])
		wyn=1;
	for (int i=2; i<n; i++)
	{
		if (wcz[i]!=wcz[1] && wcz[i+1]!=wcz[1])
			wyn=min(wyn, 2);
	}
	if (wyn==nax)
		wyn=-1;
	printf("%d\n", wyn);
	return 0;
}


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

typedef long long ll;
typedef unsigned long long ull;

#define mp make_pair
#define fr first
#define sc second

struct Graph{
	int n;
	vector<vector<pair<int,int>>> G;
	Graph(int n_){ init(n_); }
	Graph(){}
	virtual void init(int n_){
		n=n_;
		G=vector<vector<pair<int,int>>>(n,vector<pair<int,int>>());
	}
	virtual void add_edge(int u,int v,int i=0){
		G[u].push_back(mp(v,i));
	}
};

Graph g;
vector<int> num,used;
int dfs(int v,int i,int p,int k){
	if(num[v]!=-1)return k;
	num[v]=k++;
	if(i!=-1)used[i]=1;
	for(auto ed: g.G[v]){
		k=dfs(ed.fr,ed.sc,v,k);
	}
	return k;
}
void dfs_tree(int n,int m){
	num.resize(n,-1);
	used.resize(m,0);
	int k=0;
	for(int i=0;i<n;i++){
		if(num[i]==-1)k=dfs(i,-1,-1,k);
	}
}

int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	vector<int> a(m),b(m);
	for(int i=0;i<m;i++){
		scanf("%d%d",&a[i],&b[i]); a[i]--; b[i]--;
	}
	vector<int> c(n);
	for(int i=0;i<n;i++)scanf("%d",&c[i]);

	g.init(n);
	for(int i=0;i<m;i++){
		if(c[a[i]]==c[b[i]]){
			g.add_edge(a[i],b[i],i);
			g.add_edge(b[i],a[i],i);
			//cerr<<a[i]<<" "<<b[i]<<endl;
		}
	}
	dfs_tree(n,m);

	//for(int i=0;i<n;i++)cerr<<num[i]<<" "; cerr<<endl;
	//for(int i=0;i<m;i++)cerr<<used[i]<<" "; cerr<<endl;

	for(int i=0;i<m;i++){
		if(c[a[i]]!=c[b[i]]){
			if(c[a[i]]>c[b[i]])puts("->");
			else puts("<-");
		}
		else {
			int t=used[i];
			if(num[a[i]]<num[b[i]])t++;
			if(t==1)puts("<-");
			else puts("->");
		}
	}
}

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

#define int long long
#define ull unsigned long long
#define ld long double
#define rep(a) rep1(i,a)
#define rep1(i,a) rep2(i,0,a)
#define rep2(i,b,a) for(int i=(b); i<((int)(a)); i++)
#define rep3(i,b,a) for(int i=(b); i>=((int)(a)); i--)
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define pb push_back
//#define inf 1010000000
#define inf 4000000000000000000
#define eps 1e-9
#define sz(a) ((int)a.size())
#define pow2(x) (1ll<<(x))
#define ceiling(a,b) (((a)+(b)-1)/(b))
#define print0(a) cout << (a) << ' '
#define ykh mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define ordered_set tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>
#ifdef i_am_noob
#define bug(...) cerr << "#" << __LINE__ << ' ' << #__VA_ARGS__ << "- ", _do(__VA_ARGS__)
template<typename T> void _do(T && x) {cerr << x << endl;}
template<typename T, typename ...S> void _do(T && x, S&&...y) {cerr << x << ", "; _do(y...);}
#else
#define bug(...) 826
#endif
template<typename T> void print(T && x) {cout << x << "\n";}
template<typename T, typename... S> void print(T && x, S&&... y) {cout << x << ' ';print(y...);}

const int Mod=1000000007,Mod2=998244353;
const int MOD=Mod;
const int maxn=100005;
//i_am_noob
int n,m,e[maxn][3],a[105];
vector<pii> adj[105];
bool vis[105];

void dfs(int u, int par){
    vis[u]=true;
    for(auto p: adj[u]){
        int v=p.first;
        if(vis[v]){
            if(e[p.second>=0?p.second:-p.second-1][2]==2){
                if(p.second>=0) e[p.second][2]=1;
                else e[-p.second-1][2]=0;
            }
            continue;
        }
        if(e[p.second>=0?p.second:-p.second-1][2]==2){
            if(p.second>=0) e[p.second][2]=1;
            else e[-p.second-1][2]=0;
        }
        dfs(v,u);
    }
}

signed main(){
    ios_base::sync_with_stdio(0),cin.tie(0);
    #ifdef i_am_noob
    freopen("input1.txt","r",stdin);
    freopen("output1.txt","w",stdout);
    #endif
    cin >> n >> m;
    rep(m){
        cin >> e[i][0] >> e[i][1];
        e[i][0]--,e[i][1]--;
    }
    rep(n) cin >> a[i];
    rep(m){
        if(a[e[i][0]]>a[e[i][1]]) e[i][2]=1;
        else if(a[e[i][0]]<a[e[i][1]]) e[i][2]=0;
        else adj[e[i][0]].pb({e[i][1],i}),adj[e[i][1]].pb({e[i][0],-i-1}),e[i][2]=2;
    }
    rep(n) if(!vis[i]) dfs(i,-1);
    rep(m){
        if(e[i][2]==2)  print("a");
        print(e[i][2]?"->":"<-");
    }
    return 0;
}


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
using std::cout;
using std::cin;
using std::string;
using std::vector;
using std::endl;

int main()
{
    const long long mod = 998244353;
    int h, w;
    cin >> h >> w;
    vector<string> graph(h);
    for (int i = 0; i < h; i++) {
        cin >> graph[i];
    }
    long long ans = 1;
    int groups = 0;
    for (int i = 0; i < h; i++) {
        if (ans == 0) break;
        int y = i;
        int x = 0;
        char diag = '.';
        while (y >= 0 && x <= w - 1) {
            if (graph[y][x] == 'R') {
                if (diag == 'B') ans = 0;
                else diag = 'R';
            }
            if (graph[y][x] == 'B') {
                if (diag == 'R') ans = 0;
                else diag = 'B';
            }
            y--;
            x++;
        }
        if (diag == '.') {
            groups++;
        }
    }
    for (int i = 1; i < w; i++) {
        if (ans == 0) break;
        int y = h - 1;
        int x = i;
        char diag = '.';
        while (y >= 0 && x <= w - 1) {
            if (graph[y][x] == 'R') {
                if (diag == 'B') ans = 0;
                else diag = 'R';
            }
            if (graph[y][x] == 'B') {
                if (diag == 'R') ans = 0;
                else diag = 'B';
            }
            y--;
            x++;
        }
        if (diag == '.') {
            groups++;
        }
    }
    if (ans != 0) {
        for (int i = 0; i < groups; i++) {
            ans = ans * 2 % mod;
        }
    }
    cout << ans;
    return 0;
}

#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include<bits/stdc++.h>
//gouravrj code:P
using namespace std;
#define fo(i,n) for(int i=0;i<n;i++)
#define Fo(i,k,n) for(int i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define ll long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define tr(it, a) for(auto it = a.begin(); it != a.end(); it++)
#define PI 3.1415926535897932384626
#define INF  0x3f3f3f3f3f3f3f3fLL

typedef pair<int, int>  pii;
typedef pair<ll, ll>  pl;
typedef vector<int>   vi;
typedef vector<ll>    vl;
typedef vector<pii>   vpii;
typedef vector<pl>    vpl;
typedef vector<vi>    vvi;
typedef vector<vl>    vvl;

const int mod = 1000000007;
const int N = 3e5, M = N;
/*******************************************************************************************/
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "["; for (int i = 0; i < v.size(); ++i) {if (i) os << ", "; os << v[i]; }
    os << "]\n"; return os;
}
template <typename T> ostream& operator<<(ostream& os, const set<T>& v) {
    os << "{"; for (auto it : v) { os << it; if (it != *v.rbegin()) os << ", "; } os << "}\n";
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const multiset<T>& v) {
    os << "{"; for (auto it : v) { os << it; if (it != *v.rbegin()) os << ", "; } os << "}\n";
    return os;
}
template <typename T, typename S> ostream& operator<<(ostream& os, const map<T, S>& v) {
    os << "{"; for (auto it : v) { os << "(" << it.first << " : " << it.second << ")"; if (it != *v.rbegin()) os << ", "; } os << "}\n"; return os;
}
template <typename T, typename S> ostream& operator<<(ostream& os, const unordered_map<T, S>& v) {
    os << "{"; for (auto it : v) { os << "(" << it.first << " : " << it.second << ")"; os << ", "; } os << "}\n";
    return os;
}
template <typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& v) {
    os << "("; os << v.first << ", " << v.second << ")";
    return os;
}
template <typename T> inline istream &operator>>(istream &in, vector<T> &a) {
    for (auto &x : a) in >> x;
    return in;
}
#ifndef ONLINE_JUDGE
    const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[0;31m", BRIGHT_CYAN = "\033[1;36m";
    vector<string> tokenizer(const string args) {
    	string tk = args; vector<string> v;
    	for (int i = 0; i < tk.size(); i++) {
        	string s = ""; int j = i;
       		while (j < tk.size() && tk[j] != ',')s += tk[j++];
        	i = j; v.push_back(s);
    	}
    reverse(all(v));
    	return v;
    }
    void debugg(vector<string> args) { cerr << "\b\b "; }
    template <typename Head, typename... Tail>
    void debugg(vector<string>args, Head H, Tail... T) {
    	if (!sz(args))return ;
    	cerr << " [" << BRIGHT_CYAN << args.back() << ": " << BRIGHT_GREEN << H << COLOR_RESET << "] ";
    	if (sz(args)) {args.pop_back(); debugg(args, T...);}
    }
    #define deb(...) { debugg(tokenizer(#__VA_ARGS__), __VA_ARGS__, __LINE__);cerr<<'\n'; }
#endif
#ifdef ONLINE_JUDGE
    #define deb(...)
#endif

/*******************************************************************************************/

void run_case() {
    ll int t, i, j, k, p,  x, y, u,  n, m, w;

    ll A,B;
    cin>>A>>B;
    long double ans=A*(B/(100*1.0));
    cout<<fixed<<setprecision(8)<<ans<<'\n';

}//end

/*******************************************************************************************/

int main() {
    cin.tie(0)->sync_with_stdio(0);
#ifndef ONLINE_JUDGE
    //freopen("/home/gourav/input1.txt", "r", stdin); freopen("/home/gourav/output1.txt", "w", stdout);
    //freopen("error.txt", "w", stderr);
#endif
    int t = 1;
    //int T;
    // cin >> t;
    Fo(T, 1, t + 1) {
        // cout<<"Case #"<<T<<": ";
        run_case();
    }
    cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
    return 0;
}


#include <cstdio>
const double eps=1e-6;

int n;

double a[100005];

inline double min(double a,double b) {
	return a<b?a:b;
}

double calc(double x) {
	double ans=0;
	for(int i=1;i<=n;i++) {
		ans+=x+a[i]-min(a[i],x*2.0);
	}
	//printf("%.6lf %.6lf\n",x,ans);
	return ans;
}

int main() {
	scanf("%d",&n);
	for(int i=1;i<=n;i++) {
		scanf("%lf",&a[i]);
	}
	double l=0.0,r=1e9;
	while((r-l)>eps) {
		double a=l+(r-l)/3.0;
		double b=r-(r-l)/3.0;
		if(calc(a)<calc(b)) {
			r=b;
		}else {
			l=a;
		}
	}
	printf("%.6lf\n",min(calc(l),calc(r))/(1.0*n));
	return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
#include <cassert>
#define rep(i,n) for(int i = 0; i < n; ++i )
using namespace std;
using ll = long long;

ll x[100005],y[100005];
int main() {
  int n;
  cin >> n;
  rep(i,n){
    int a;
    cin >> a;
    x[a]++;
  }
  vector<int> b(n);
  rep(i,n) cin >> b[i];
  rep(i,n){
    int c;
    cin >> c;
    --c;
    y[b[c]]++;
  }
  ll ans = 0;
  rep(i,n+1) ans += x[i]*y[i];
  cout << ans << endl;
}


#include <bits/stdc++.h>

#define  LL long long

const int maxn=1e5+5;
using namespace std;
LL ans=0;
int  op[80];
LL ans1[80];
LL ans2[80];
int main()
{
    LL n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        string s;
        cin>>s;
        if(s=="AND")
            op[i]=1;
        else
            op[i]=0;
    }
    memset(ans1,0,sizeof(ans1));
    memset(ans2,0,sizeof(ans2));
    ans1[0]=1;
    ans2[0]=1;
    for(int i=1;i<=n;i++)
    {
        if(op[i]==1)  ///and
        {
            ans1[i]=ans1[i-1];
            ans2[i]=ans1[i-1]+ans2[i-1]*2;
        }
        else          ///or
        {
            ans1[i]=ans1[i-1]*2+ans2[i-1];
            ans2[i]=ans2[i-1];
        }
    }
    /*for(int i=0;i<=n;i++)
        cout<<ans1[i]<<" ";
    cout<<endl;
    for(int i=0;i<=n;i++)
        cout<<ans2[i]<<" ";
    cout<<endl;*/
    cout<<ans1[n]<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i = 0; i < (n); ++i)
using ll = long long;
using P = pair<int,int>;
int main() {
  int n;
  cin >> n;
  vector<ll> dp(2, 1);
  vector<ll> ndp(2, 0);
  rep(i,n) {
    string s;
    cin >> s;
    rep(xi,2) {
      rep(xi1,2) {
        int yi1;
        if (s == "AND") {
          yi1 = xi & xi1;
        } else {
          yi1 = xi | xi1;
        }
        ndp[yi1] += dp[xi];
      }
    }
    swap(ndp, dp);
    ndp.clear();
    ndp.resize(2);
  }
  ll ans = dp[1];
  cout << ans << endl;
  return 0;
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author Pine1999
 */

#include <bits/stdc++.h>

using namespace std;

void CNeqMin(std::istream& in, std::ostream& out) {
    int n;
    in >> n;
    vector<int> p(n);
    vector<bool> exist(400050);
    int ans = 0;
    for (int i = 0; i < n; ++i) {
        in >> p[i];
        exist[p[i]] = true;
        while (exist[ans]) ++ans;
        out << ans << '\n';
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    std::istream& in(std::cin);
    std::ostream& out(std::cout);
    CNeqMin(in, out);
    return 0;
}

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

#define ff first
#define ss second
#define int long long
#define pb push_back
#define mp make_pair
#define pii pair<int, int>
#define vi vector<int>
#define mii map<int, int>
#define pqb priority_queue<int>
#define pqs priority_queue<int, vi, greater<int>>
#define mod 1000000007
#define ps(x, y) fixed << setprecision(y) << x
#define w(x)  \
    int x;    \
    cin >> x; \
    while (x--)
#define fastIO                    \
    ios_base::sync_with_stdio(0); \
    cin.tie(0);                   \
    cout.tie(0)
#define fo(i, n) for (int i = 0; i < n; i++)
#define Fo(i, k, n) for (int i = k; i < n; i++)

int32_t main(){
string str;
cin >> str;
int count = 0;
for(int i = 0; i < str.size(); i++){
    if(str[i]=='Z' && str[i+1]=='O' && str[i+2]=='N' && str[i+3]=='e'){
        count++;
        i += 3;
    }
}
cout << count << endl;
    return 0;
}