#include <bits/stdc++.h>
using namespace std;
template <class T>
bool umin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
bool umax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
struct node {
  int c, h, t;
  void make(int _c, int _h, int _t) {
    c = _c;
    h = _h;
    t = _t;
  }
  bool operator<(node x) const { return (t < x.t); }
  void show() { printf("%d %d %d\n", c, h, t); }
} S[4009], olimp[4009], centr[4009];
struct query {
  int a, b, ind;
  void make(int _a, int _b, int _ind) {
    a = _a;
    b = _b;
    ind = _ind;
  }
  bool operator<(query x) const { return (a < x.a); }
} Q[20009];
int ans[20009];
int dp[2][4009][4009];
int main() {
  int n, p;
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    int cc, hh, tt;
    scanf("%d%d%d", &cc, &hh, &tt);
    S[i].make(cc, hh, tt);
  }
  sort(S + 1, S + n + 1);
  int cnt = 1, q;
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    int aa, bb;
    scanf("%d%d", &aa, &bb);
    Q[i].make(aa, bb, i);
  }
  sort(Q + 1, Q + q + 1);
  int pnt = 1;
  for (int i = 0; i <= 20000; i += p) {
    int cep = 0, sag = 0;
    while (pnt <= n and S[pnt].t < i) pnt++;
    for (int j = pnt - 1; j >= 1 and S[j].t >= i - p + 1; j--)
      olimp[++cep] = S[j];
    for (int j = pnt; j <= n and S[j].t < i + p; j++) centr[++sag] = S[j];
    for (int j = 4000; j >= 1; j--) dp[0][0][i] = dp[1][0][i] = 0;
    for (int j = 1; j <= cep; j++)
      for (int k = 0; k <= 4000; k++) {
        dp[0][j][k] = dp[0][j - 1][k];
        if (k - olimp[j].c >= 0)
          umax(dp[0][j][k], dp[0][j - 1][k - olimp[j].c] + olimp[j].h);
      }
    for (int j = 1; j <= sag; j++)
      for (int k = 0; k <= 4000; k++) {
        dp[1][j][k] = dp[1][j - 1][k];
        if (k - centr[j].c >= 0)
          umax(dp[1][j][k], dp[1][j - 1][k - centr[j].c] + centr[j].h);
      }
    int lt = cep, rt = 0;
    while (cnt <= q and Q[cnt].a < i + p) {
      int cost = Q[cnt].b;
      while (lt >= 1 and olimp[lt].t <= Q[cnt].a - p) lt--;
      while (rt + 1 <= sag and centr[rt + 1].t <= Q[cnt].a) rt++;
      for (int j = 0; j <= cost; j++)
        umax(ans[Q[cnt].ind], dp[0][lt][j] + dp[1][rt][cost - j]);
      cnt++;
    }
    if (cnt > q) break;
  }
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
