#include <bits/stdc++.h>
const int N = 4005, T = 20005;
using namespace std;
int l[N * N], r[N * N], f[T], idl[T], idr[T], n, p, x, y, z, mx, A, B, ans, q,
    cl, cr;
vector<int> v[T], w[T];
int P(int y, int z) {
  if (y < 0 || z < 0) return 0;
  if (y * B + z > N * N) return 2;
  return y * B + z;
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++)
    scanf("%d%d%d", &x, &y, &z), v[z].push_back(x), w[z].push_back(y),
        mx = max(mx, z + p - 1);
  B = N;
  for (int i = 0; i <= mx; i += p) {
    memset(f, 0, sizeof(f));
    for (int j = i; j > i - p && j > 0; j--) {
      for (int l = 0; l < v[j].size(); l++)
        for (int k = N - 1; k >= v[j][l]; k--)
          f[k] = max(f[k], f[k - v[j][l]] + w[j][l]);
      for (int k = 1; k < N; k++) f[i] = max(f[i], f[i - 1]);
      if (v[j].size()) {
        idl[j] = ++cl;
        for (int k = 0; k < N; k++) l[P(cl, k)] = f[k];
      } else if (j == i)
        idl[j] = 0;
      else
        idl[j] = idl[j + 1];
    }
    memset(f, 0, sizeof(f));
    for (int j = i + 1; j < i + p && j <= mx; j++) {
      for (int l = 0; l < v[j].size(); l++)
        for (int k = N - 1; k >= v[j][l]; k--)
          f[k] = max(f[k], f[k - v[j][l]] + w[j][l]);
      for (int k = 1; k < N; k++) f[i] = max(f[i], f[i - 1]);
      if (v[j].size()) {
        idr[j] = ++cr;
        for (int k = 0; k < N; k++) r[P(cr, k)] = f[k];
      } else if (j == i + 1)
        idr[j] = 0;
      else
        idr[j] = idr[j - 1];
    }
  }
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    scanf("%d%d", &x, &y), ans = 0;
    if (x <= mx)
      if (x < p)
        ans = r[P(idr[x], y)];
      else
        for (int i = 0; i <= y; i++)
          ans = max(ans, l[P(idl[x - p + 1], i)] + r[P(idr[x], y - i)]);
    printf("%d\n", ans);
  }
}
