#include <bits/stdc++.h>
using namespace std;
const int maxn = 4000 + 233;
const int maxq = 2e4 + 233;
struct goods {
  int c, v, t;
} a[maxn];
bool cmp(const goods A, const goods B) { return A.t < B.t; }
int ans[maxq], ql[maxq], qr[maxq], b[maxq], tt[maxn];
void work(int l, int r, vector<int> cur) {
  if (l == r) {
    for (int i = 0; i < cur.size(); i++) {
      int j = cur[i];
      if (b[j] >= a[l].c)
        ans[j] = a[l].v;
      else
        ans[j] = 0;
    }
    return;
  }
  int mid = (l + r) >> 1;
  vector<int> L, R;
  int Lef = 0;
  for (int i = 0; i < cur.size(); i++) {
    int j = cur[i];
    if (qr[j] <= mid) L.push_back(j);
    if (ql[j] >= mid + 1) R.push_back(j);
    Lef++;
  }
  if (L.size()) work(l, mid, L);
  if (R.size()) work(mid + 1, r, R);
  if (!Lef) return;
  int siz = (r - l) >> 1;
  siz += 5;
  int per[siz][maxn], suf[siz][maxn];
  memset(per, 0, sizeof(per));
  memset(suf, 0, sizeof(suf));
  for (int i = mid; i >= l; i--) {
    int c = a[i].c, v = a[i].v;
    int j = mid - i + 1;
    for (int k = 0; k < c; k++) per[j][k] = per[j - 1][k];
    for (int k = c; k <= 4000; k++)
      per[j][k] = per[j - 1][k] < per[j - 1][k - c] + v ? per[j - 1][k - c] + v
                                                        : per[j - 1][k];
  }
  for (int i = mid + 1; i <= r; i++) {
    int c = a[i].c, v = a[i].v;
    int j = i - mid;
    for (int k = 0; k < c; k++) suf[j][k] = suf[j - 1][k];
    for (int k = c; k <= 4000; k++)
      suf[j][k] = suf[j - 1][k] < suf[j - 1][k - c] + v ? suf[j - 1][k - c] + v
                                                        : suf[j - 1][k];
  }
  for (int i = 0; i < cur.size(); i++) {
    int j = cur[i];
    if (qr[j] <= mid) continue;
    if (ql[j] >= mid + 1) continue;
    ans[j] = 0;
    int x = mid - ql[j] + 1;
    int y = qr[j] - mid;
    for (int k = 0; k <= b[j]; k++)
      ans[j] = ans[j] < per[x][k] + suf[y][b[j] - k]
                   ? per[x][k] + suf[y][b[j] - k]
                   : ans[j];
  }
  return;
}
int main() {
  int n, p;
  cin >> n >> p;
  for (int i = 1; i <= n; i++) scanf("%d%d%d", &a[i].c, &a[i].v, &a[i].t);
  sort(a + 1, a + 1 + n, cmp);
  for (int i = 1; i <= n; i++) tt[i] = a[i].t;
  int q;
  cin >> q;
  vector<int> Q;
  for (int i = 1; i <= q; i++) {
    int t;
    scanf("%d%d", &t, &b[i]);
    ql[i] = lower_bound(tt + 1, tt + 1 + n, t - p + 1) - tt;
    qr[i] = upper_bound(tt + 1, tt + 1 + n, t) - tt - 1;
    if (qr[i] == 0 || ql[i] == n + 1 || ql[i] > qr[i]) {
      ans[i] = 0;
      continue;
    }
    Q.push_back(i);
  }
  work(1, n, Q);
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
