#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
using namespace std;

#define int long long int
#define double long double

#define all(x) begin(x), end(x)
#define Done(x) cout<<x<<endl; return;
#define endl '\n'

void solve(){
	int n; cin>>n;
	int m; cin>>m;
	map<int,int>occur;
	for(int i=0;i<n;i++){
		int a; cin>>a;
		int b; cin>>b; b++;
		int c; cin>>c;
		occur[a]+=c;
		occur[b]-=c;
	}
	int ans=0;
	int curr=0;
	int last=0;
	for(auto p:occur){
		int dist=p.first-last;
		ans+=dist*min(curr,m);
		last=p.first;
		curr+=p.second;
	}
	cout<<ans<<endl;
}

int32_t main(){
	// Remove for Interactive Problems
	ios_base::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	solve();
	
	cerr<<"Time : "<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<"ms\n";
	return 0;
}
    #include <bits/stdc++.h>
    using namespace std;
    #include <math.h>
    #include <iomanip>
    #include <cstdint>
    #include <string>
    #include <sstream>
    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; }
    #define rep(i,n) for (int i = 0; i < (n); ++i)
    typedef long long ll;
    using P=pair<ll,ll>;
    const int INF=1001001001;
    const int mod=998244353;
    
    vector<int>G[200005],r[200005];
    int in[200005],out[200005],depth[200005];
    int id;

    void dfs(int i,int d=0){
      in[i]=id++;
      depth[i]=d;
      for(int u:G[i]){dfs(u,d+1);}
      out[i]=id;
    }

    void solve(){
      int n;
      cin>>n;
      rep(i,n-1){
        int p;
        cin>>p;
        p--;
        G[p].push_back(i+1);
      }
      dfs(0);
      rep(i,n){r[depth[i]].push_back(in[i]);}
      rep(i,n){sort(r[i].begin(),r[i].end());}
      int Q;
      cin>>Q;
      rep(i,Q){
        int u,d;
        cin>>u>>d;
        u--;
        int ans=lower_bound(r[d].begin(),r[d].end(),out[u])-lower_bound(r[d].begin(),r[d].end(),in[u]);
        cout<<ans<<endl;
      }
    }
    int main(){
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      solve();
      return 0;
    }