#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;
int C[M], H[M], T[M], pre[M][M], suf[M][M];
int n, m, p, q;
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);
  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(C[j], C[j - 1]);
        swap(H[j], H[j - 1]);
        swap(T[j], T[j - 1]);
      }
  for (int i = (0), i_end__ = (n); i < i_end__; ++i) {
    if (i and T[i] / p == T[i - 1] / p)
      memcpy(pre[i], pre[i - 1], sizeof(pre[i]));
    for (int j = (M)-1, j_end__ = (C[i]); j_end__ <= j; --j)
      chkmax(pre[i][j], pre[i][j - C[i]] + H[i]);
  }
  for (int i = (n)-1, i_end__ = (0); i_end__ <= i; --i) {
    if (i < n - 1 and T[i] / p == T[i + 1] / p)
      memcpy(suf[i], suf[i + 1], sizeof(suf[i]));
    for (int j = (M)-1, j_end__ = (C[i]); j_end__ <= j; --j)
      chkmax(suf[i][j], suf[i][j - C[i]] + H[i]);
  }
  for (scanf("%d", &q); q; --q) {
    int a, b;
    scanf("%d%d", &a, &b);
    int l = upper_bound(T, T + n, a - p) - T;
    int r = upper_bound(T, T + n, a) - T - 1;
    if (l > r)
      puts("0");
    else if (T[l] / p == T[r] / p) {
      if (!l or T[l - 1] / p != T[l] / p)
        printf("%d\n", pre[r][b]);
      else
        printf("%d\n", suf[l][b]);
    } else {
      int ans = 0;
      for (int i = (0), i_end__ = (b + 1); i < i_end__; ++i)
        chkmax(ans, suf[l][i] + pre[r][b - i]);
      printf("%d\n", ans);
    }
  }
  return 0;
}
