#include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool chkmin(T& a, T const& b) {
  return b < a ? a = b, true : false;
}
template <class T>
inline bool chkmax(T& a, T const& b) {
  return a < b ? a = b, true : false;
}
const int M = 4005;
const int S = 40;
const int N = M / S + 3;
int C[M], H[M], T[M], sx[M << 1];
int dp[M], tmp[M], ans[M << 1][M];
int n, m, p, q;
struct atom {
  int l, r, i;
  inline bool operator<(atom const& _) const { return r < _.r; }
};
vector<atom> Q[N];
int main() {
  scanf("%d%d", &n, &p);
  for (int i = (0), i_end__ = (n); i < i_end__; ++i)
    scanf("%d%d%d", C + i, H + i, T + i);
  scanf("%d", &q);
  for (int i = (0), i_end__ = (n); i < i_end__; ++i)
    for (int j = (1), j_end__ = (n - i); j < j_end__; ++j)
      if (T[j] < T[j - 1]) {
        swap(T[j], T[j - 1]);
        swap(H[j], H[j - 1]);
        swap(C[j], C[j - 1]);
      }
  for (int i = (0), i_end__ = (n); i < i_end__; ++i)
    sx[m++] = T[i], sx[m++] = T[i] + p;
  sort(sx, sx + m);
  m = unique(sx, sx + m) - sx;
  for (int i = (0), i_end__ = (m); i < i_end__; ++i) {
    int t = sx[i], l = -1, r = -1;
    for (int j = (n)-1, j_end__ = (0); j_end__ <= j; --j)
      if (T[j] <= t and t < T[j] + p) l = j;
    for (int j = (0), j_end__ = (n); j < j_end__; ++j)
      if (T[j] <= t and t < T[j] + p) r = j;
    if (l < 0 or r < 0) continue;
    if (r - l < S) {
      memset(dp, 0, sizeof(dp));
      for (int j = (l), j_end__ = (r + 1); j < j_end__; ++j) {
        int c = C[j], h = H[j];
        for (int i = (M)-1, i_end__ = (c); i_end__ <= i; --i)
          chkmax(dp[i], dp[i - c] + h);
      }
      memcpy(ans[i], dp, sizeof(dp));
    } else
      Q[l / S].push_back((atom){l, r, i});
  }
  for (int p = (0), p_end__ = (N); p < p_end__; ++p)
    if (!Q[p].empty()) {
      memset(dp, 0, sizeof(dp));
      sort(Q[p].begin(), Q[p].end());
      int r = (p + 1) * S - 1;
      for (int j = (0), j_end__ = (Q[p].size()); j < j_end__; ++j) {
        atom q = Q[p][j];
        while (r < q.r) {
          ++r;
          int c = C[r], h = H[r];
          for (int i = (M)-1, i_end__ = (c); i_end__ <= i; --i)
            chkmax(dp[i], dp[i - c] + h);
        }
        for (int i = (0), i_end__ = (M); i < i_end__; ++i) tmp[i] = dp[i];
        for (int i = (q.l), i_end__ = ((p + 1) * S); i < i_end__; ++i) {
          int c = C[i], h = H[i];
          for (int i = (M)-1, i_end__ = (c); i_end__ <= i; --i)
            chkmax(dp[i], dp[i - c] + h);
        }
        memcpy(ans[q.i], dp, sizeof(dp));
        for (int i = (0), i_end__ = (M); i < i_end__; ++i) dp[i] = tmp[i];
      }
    }
  while (q--) {
    int a, b;
    scanf("%d%d", &a, &b);
    int p = upper_bound(sx, sx + m, a) - sx - 1;
    if (p < 0)
      puts("0");
    else
      printf("%d\n", ans[p][b]);
  }
  return 0;
}
