#include <bits/stdc++.h>
using namespace std;
int n, p, L[20005], R[20005], cnt = 0;
vector<pair<int, int> > a[20005];
struct Dp {
  int f[4005];
} dp[4005 << 1];
void operator+=(Dp &a, const pair<int, int> &x) {
  for (int i = 4005 - 1; i >= x.first; i--)
    a.f[i] = max(a.f[i], a.f[i - x.first] + x.second);
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    int c, h, t;
    scanf("%d%d%d", &c, &h, &t);
    a[t].push_back(make_pair(c, h));
  }
  for (int i = 1; i <= 20005 - 5; i += p) {
    for (int j = 0; j < p && i + j <= 20005 - 5; j++) {
      if (j) R[i + j] = R[i + j - 1];
      if (a[i + j].size()) {
        dp[++cnt] = dp[R[i + j]], R[i + j] = cnt;
        for (int k = 0, sz = a[i + j].size(); k < sz; k++)
          dp[cnt] += a[i + j][k];
      }
    }
    for (int j = 1; j < p && i - j > 0; j++) {
      if (j > 1) L[i - j] = L[i - j + 1];
      if (a[i - j].size()) {
        dp[++cnt] = dp[L[i - j]], L[i - j] = cnt;
        for (int k = 0, sz = a[i - j].size(); k < sz; k++)
          dp[cnt] += a[i - j][k];
      }
    }
  }
  int q;
  scanf("%d", &q);
  while (q--) {
    int ans = 0;
    int x, y;
    scanf("%d%d", &x, &y);
    for (int i = 0; i <= y; i++)
      ans = max(
          ans, dp[(x - p + 1 > 0 ? L[x - p + 1] : 0)].f[i] + dp[R[x]].f[y - i]);
    printf("%d\n", ans);
  }
  return 0;
}
