#include <bits/stdc++.h>
using namespace std;
const int M = 4000;
const int V = M;
const int bsz = 64;
int n, p;
int c[M + 5], h[M + 5], t[M + 5], C[M + 5], _c[M + 5], _h[M + 5], _t[M + 5];
int ldp[M + 5][V + 5], rdp[M + 5][V + 5];
inline void rd(int& res) { scanf("%d", &res); }
bool cmp(int a, int b) { return _t[a] < _t[b]; }
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1, i_END_ = n + 1; i < i_END_; ++i) {
    rd(_c[i]);
    rd(_h[i]);
    rd(_t[i]);
  }
  for (int i = 1, i_END_ = n + 1; i < i_END_; ++i) C[i] = i;
  sort(C + 1, C + n + 1, cmp);
  for (int i = 1, i_END_ = n + 1; i < i_END_; ++i)
    c[i] = _c[C[i]], h[i] = _h[C[i]], t[i] = _t[C[i]];
  t[0] = t[n + 1] = -p;
  for (int i = 1, i_END_ = n + 1; i < i_END_; ++i) {
    if (t[i] / p == t[i - 1] / p) {
      for (int j = c[i], j_END_ = V + 1; j < j_END_; ++j) {
        ldp[i][j] =
            max(ldp[i][j - 1], max(ldp[i - 1][j], ldp[i - 1][j - c[i]] + h[i]));
      }
      for (int j = 0, j_END_ = c[i]; j < j_END_; ++j) ldp[i][j] = ldp[i - 1][j];
    } else {
      for (int j = c[i], j_END_ = V + 1; j < j_END_; ++j) ldp[i][j] = h[i];
    }
  }
  for (int i = (n + 1) - 1, i_BEGIN_ = 1; i >= i_BEGIN_; --i) {
    if (t[i] / p == t[i + 1] / p) {
      for (int j = c[i], j_END_ = V + 1; j < j_END_; ++j) {
        rdp[i][j] =
            max(rdp[i][j - 1], max(rdp[i + 1][j], rdp[i + 1][j - c[i]] + h[i]));
      }
      for (int j = 0, j_END_ = c[i]; j < j_END_; ++j) rdp[i][j] = rdp[i + 1][j];
    } else {
      for (int j = c[i], j_END_ = V + 1; j < j_END_; ++j) rdp[i][j] = h[i];
    }
  }
  int q;
  scanf("%d", &q);
  for (int kt = 0, kt_END_ = q; kt < kt_END_; ++kt) {
    int a, b;
    scanf("%d%d", &a, &b);
    int l = 0, r = -1;
    int lim = max(0, a - p + 1);
    for (int i = 1, i_END_ = n + 1; i < i_END_; ++i) {
      if (t[i] < lim) l = i;
      if (t[i] <= a && t[i] >= lim) r = i;
    }
    l++;
    if (l > r) {
      puts("0");
      continue;
    } else if (t[l] / p == t[r] / p) {
      if (a / p == t[l] / p)
        printf("%d\n", ldp[r][b]);
      else
        printf("%d\n", rdp[l][b]);
    } else {
      int ans = 0;
      for (int i = 0, i_END_ = b + 1; i < i_END_; ++i) {
        ans = max(ans, ldp[r][i] + rdp[l][b - i]);
      }
      printf("%d\n", ans);
    }
  }
  return 0;
}
