#include <bits/stdc++.h>
using namespace std;
const int maxn = 4050;
const int maxq = 20005;
const int maxt = 20000;
int n, p, q;
int ans[maxq];
struct goods {
  int c, v;
} gods[maxn + 50];
vector<int> gd[maxt + 50];
pair<int, pair<int, int> > que[maxq];
int fr[maxn], frn;
int bk[maxn], bkn;
int F[2][maxn + 50][maxn + 50];
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    int c, v, t;
    scanf("%d%d%d", &c, &v, &t);
    gods[i] = (goods){c, v};
    gd[t].push_back(i);
    gd[min(maxt, t + p)].push_back(-i);
  }
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    que[i].first = a;
    que[i].second.first = b;
    que[i].second.second = i;
  }
  int cur = 1;
  sort(que + 1, que + 1 + q);
  for (int i = 1; i <= maxt; i++) {
    for (int j = 0; j < gd[i].size(); j++) {
      int x = gd[i][j];
      int v, c;
      if (x > 0) {
        fr[++frn] = x;
        v = gods[fr[frn]].v, c = gods[fr[frn]].c;
        for (int i = 0; i <= maxn; i++) F[0][frn][i] = F[0][frn - 1][i];
        for (int i = maxn; i >= c; i--)
          F[0][frn][i] = max(F[0][frn][i], F[0][frn][i - c] + v);
      } else {
        if (!bkn) {
          while (frn) {
            bk[++bkn] = fr[frn--];
            v = gods[bk[bkn]].v, c = gods[bk[bkn]].c;
            for (int i = 0; i <= maxn; i++) F[1][bkn][i] = F[1][bkn - 1][i];
            for (int i = maxn - 1; i >= c; i--)
              F[1][bkn][i] = max(F[1][bkn][i], F[1][bkn][i - c] + v);
          }
        }
        bkn--;
      }
    }
    while (cur <= q && que[cur].first == i) {
      int v = que[cur].second.first;
      for (int i = 0; i <= v; i++)
        ans[que[cur].second.second] =
            max(ans[que[cur].second.second], F[0][frn][i] + F[1][bkn][v - i]);
      cur++;
    }
  }
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
