#include <bits/stdc++.h>
using namespace std;
int n, m, p, q;
struct data1 {
  int c, h, t;
} a[4005];
int pre[4005], nxt[4005], tot1, tot2, ans[20005], f1[4005][4005],
    f2[4005][4005];
vector<int> id[20005];
struct data {
  int nxt, v, id;
} Q[20005];
bool cmp(data a, data b) { return a.nxt < b.nxt; }
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    scanf("%d%d%d", &a[i].c, &a[i].h, &a[i].t);
    id[a[i].t].push_back(i);
    id[a[i].t + p].push_back(-i);
  }
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    scanf("%d%d", &Q[i].nxt, &Q[i].v);
    Q[i].id = i;
  }
  sort(Q + 1, Q + q + 1, cmp);
  int t = 1;
  for (int i = 1; i <= 20000; i++) {
    for (int j = 0; j < (int)id[i].size(); j++) {
      int now = id[i][j];
      if (now > 0) {
        pre[++tot1] = now;
        int c = a[pre[tot1]].c, h = a[pre[tot1]].h;
        for (int j = 0; j <= 4000; j++) f1[tot1][j] = f1[tot1 - 1][j];
        for (int j = c; j <= 4000; j++)
          f1[tot1][j] = max(f1[tot1][j], f1[tot1 - 1][j - c] + h);
      } else {
        if (tot2 == 0) {
          while (tot1) {
            nxt[++tot2] = pre[tot1--];
            int c = a[nxt[tot2]].c, h = a[nxt[tot2]].h;
            for (int j = 0; j <= 4000; j++) f2[tot2][j] = f2[tot2 - 1][j];
            for (int j = c; j <= 4000; j++)
              f2[tot2][j] = max(f2[tot2][j], f2[tot2 - 1][j - c] + h);
          }
        }
        tot2--;
      }
    }
    while (Q[t].nxt == i) {
      int v = Q[t].v, id = Q[t].id;
      for (int j = 0; j <= v; j++)
        ans[id] = max(ans[id], f1[tot1][j] + f2[tot2][v - j]);
      t++;
    }
  }
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
