#include <bits/stdc++.h>
using namespace std;
int n, p, x[50005], y[50005], Buc[50005], lSt, lDr, dp1[4005][4005],
    dp2[4005][4005], sol[50005];
struct segm {
  int st, dr, cost, pret;
} a[50005];
struct el {
  int capat, cost, pret;
  bool operator<(const el A) const { return capat < A.capat; }
} St[50005], Dr[50005];
struct qry {
  int t, B, ind;
  bool operator<(const qry A) const { return t < A.t; }
} b[50005];
int main() {
  int i, j, Maxx = 0, cur = 1, x, y, m, kk;
  cin.sync_with_stdio(0);
  cin >> n >> p;
  for (i = 1; i <= n; ++i) {
    cin >> a[i].pret >> a[i].cost >> a[i].st;
    a[i].dr = a[i].st + p - 1;
  }
  cin >> m;
  for (i = 1; i <= m; ++i) {
    cin >> b[i].t >> b[i].B;
    Maxx = max(Maxx, b[i].B);
    b[i].ind = i;
  }
  sort(b + 1, b + m + 1);
  for (kk = 1; 1 + (kk - 1) * p <= b[m].t; ++kk) {
    int l = 1 + (kk - 1) * p, r = kk * p;
    if (b[cur].t > r) continue;
    lSt = lDr = 0;
    for (j = 1; j <= n; ++j)
      if (a[j].st <= l && a[j].dr >= l) {
        ++lSt;
        St[lSt].capat = a[j].dr;
        St[lSt].pret = a[j].pret;
        St[lSt].cost = a[j].cost;
      }
    for (j = 1; j <= n; ++j)
      if (a[j].st <= r && a[j].dr > r) {
        ++lDr;
        Dr[lDr].capat = a[j].st;
        Dr[lDr].pret = a[j].pret;
        Dr[lDr].cost = a[j].cost;
      }
    sort(St + 1, St + lSt + 1);
    sort(Dr + 1, Dr + lDr + 1);
    for (i = 1; i <= lSt + 1; ++i)
      for (j = 0; j <= Maxx; ++j) dp1[i][j] = 0;
    for (i = lSt; i; --i)
      for (j = 0; j <= Maxx; ++j) {
        if (j) dp1[i][j] = dp1[i][j - 1];
        if (j >= St[i].pret)
          dp1[i][j] = max(dp1[i][j], dp1[i + 1][j - St[i].pret] + St[i].cost);
        dp1[i][j] = max(dp1[i][j], dp1[i + 1][j]);
      }
    for (i = 0; i <= lDr; ++i)
      for (j = 0; j <= Maxx; ++j) dp2[i][j] = 0;
    for (i = 1; i <= lDr; ++i)
      for (j = 0; j <= Maxx; ++j) {
        if (j) dp2[i][j] = dp2[i][j - 1];
        if (j >= Dr[i].pret)
          dp2[i][j] = max(dp2[i][j], dp2[i - 1][j - Dr[i].pret] + Dr[i].cost);
        dp2[i][j] = max(dp2[i][j], dp2[i - 1][j]);
      }
    x = 1;
    y = 0;
    for (; cur <= m && b[cur].t <= r; ++cur) {
      while (x <= lSt && St[x].capat < b[cur].t) ++x;
      while (y < lDr && Dr[y + 1].capat <= b[cur].t) ++y;
      for (i = 0; i <= b[cur].B; ++i)
        sol[b[cur].ind] =
            max(sol[b[cur].ind], dp1[x][i] + dp2[y][b[cur].B - i]);
    }
  }
  for (i = 1; i <= m; ++i) cout << sol[i] << "\n";
  return 0;
}
