#include <bits/stdc++.h>
using namespace std;
static pair<int, int> m1[5000];
static int n, m, d[5000], dp[5000][5000], p, day[5000], res[500000];
static vector<vector<int> > vc;
static vector<vector<pair<int, int> > > vc1;
void dd(int ct) {
  int bg = max(1, ct - p), en = min((int)vc.size() - 1, ct + p - 1), x, y,
      c = 0, pv;
  memset(d, 0, sizeof(d));
  for (int i = ct - 1; i >= bg; --i) {
    for (int j = 0; j < vc[i].size(); ++j) {
      day[++c] = i;
      for (int k = 1; k <= 4000; ++k) {
        dp[c][k] = max(dp[c][k - 1], dp[c - 1][k]);
        if (k >= m1[vc[i][j]].first)
          dp[c][k] = max(dp[c][k], dp[c - 1][k - m1[vc[i][j]].first] +
                                       m1[vc[i][j]].second);
      }
    }
  }
  pv = c;
  for (int i = ct; i <= en; ++i) {
    for (int j = 0; j < vc[i].size(); ++j) {
      for (int k = 4000; k >= m1[vc[i][j]].first; --k) {
        d[k] = max(d[k], d[k - m1[vc[i][j]].first] + m1[vc[i][j]].second);
      }
    }
    while (pv && day[pv] <= i - p) --pv;
    for (int j = 0; j < vc1[i].size(); ++j) {
      for (int k = 0; k <= vc1[i][j].first; ++k)
        res[vc1[i][j].second] =
            max(res[vc1[i][j].second], dp[pv][k] + d[vc1[i][j].first - k]);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> p;
  int t, c;
  vc.resize(200050);
  vc1.resize(200050);
  for (int i = 1; i <= n; ++i) {
    cin >> m1[i].first >> m1[i].second >> t;
    vc[t].push_back(i);
  }
  cin >> m;
  for (int i = 1; i <= m; ++i) {
    cin >> t >> c;
    vc1[t].push_back(make_pair(c, i));
  }
  for (int i = 1; i < 200050; i += p) dd(i);
  for (int i = 1; i <= m; ++i) cout << res[i] << '\n';
  return 0;
}
